0%

121. 买卖股票的最佳时机

贪心

因为只能买卖一次,枚举卖出日时,只要知道它之前的最低价格即可。遍历数组,维护历史最低价 preMin,用当前价格减去 preMin 更新最大利润。

时间复杂度

空间复杂度

1
2
3
4
5
6
7
8
9
10
class Solution {
public int maxProfit(int[] prices) {
int ans = 0, preMin = prices[0];
for (int i = 1; i < prices.length; ++i) {
ans = Math.max(ans, prices[i] - preMin);
preMin = Math.min(preMin, prices[i]);
}
return ans;
}
}