LeetCode 121 Best Time to Buy and Sell Stock 贪心
作者:互联网
You are given an array prices where prices[i]
is the price of a given stock on the \(i\)th day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return \(0\).
Solution
很简单的贪心策略,遍历的时候维护一个最小值即可,然后更新最大的 \(prices[i]-\min\)
点击查看代码
class Solution {
private:
int Min = 100000;
int ans = -1;
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n==1)return 0;
int Min = min(Min, prices[0]);
for(int i=1;i<n;i++){
Min = min(Min, prices[i]);
ans = max(ans, prices[i]-Min);
}
if(ans==-1)return 0;
else return ans;
}
};
标签:Sell,Buy,Min,int,profit,121,prices,day,stock 来源: https://www.cnblogs.com/xinyu04/p/16496436.html