122. 买卖股票的最佳时机 II

解法一

贪心
如果今天的股价高于昨天,那么就可以卖出赚差价,将所有的股价看成一个折线图📈,将所有的上升部分加起来就是最高的利润。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
// 买卖股价的最佳时机
// 贪心
let profile = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profile += prices[i] - prices[i - 1];
}
}
return profile;
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。