122. Best Time to Buy and Sell Stock II - Medium
前往題目
想法
- 用
DP
然後分買與不買
思路
可以用複雜的dp
但也可以藉由觀察找到最簡單又最優的解
- 從第二個開始疊代,每次都和前一個比較
- 如果比上一個大就加到
profit
裡
因為都在高點賣出,而且可以當天買進,不需要冷卻時間
Code
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 1; i < prices.length; ++i) {
// 與前一個比較
if (prices[i] > prices[i - 1]) {
// 比較大就加到profit裡
res += (prices[i] - prices[i - 1]);
}
}
return res;
}
}
122. Best Time to Buy and Sell Stock II - Medium
https://f88083.github.io/2024/03/19/122-Best-Time-to-Buy-and-Sell-Stock-II-Medium/