121. Best Time to Buy and Sell Stock

解法

貪心法,紀錄先前最小值,在跟每天的價格比對就好。

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int minn = 10020;

for(int i = 0; i < prices.size(); i++){
minn = min(prices[i], minn);
ans = max(ans, prices[i] - minn);
}
return ans;
}
};
  • 版權聲明: 本部落格所有文章除有特別聲明外,均採用 Apache License 2.0 許可協議。轉載請註明出處!
  • © 2020-2024 John Doe
  • Powered by Hexo Theme Ayer
  • PV: UV: