[Leetcode] Best Time to Buy Stock
考虑,股票的价格是不断变化的,卖出只能在买入后进行。而且只能买入卖出一次。
开始的时候想扫一遍,求最大最小,但是肯定不会这么简单。你484傻
因为只能卖出一次,若i天卖出,可能的盈利值是, prices[i] - min,就是今天的价格。
再将这个值与之前可能的最大值比较,可以得到 第i天可能的最大值。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
int minPrice = prices[0];
int n = prices.size();
int maxProfit = 0;
for (int i =0; i<n; ++i) {
minPrice = min(minPrice, prices[i]);
maxProfit = max(maxProfit,prices[i] - minPrice);
}
return maxProfit;
}
};

浙公网安备 33010602011771号