原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
解题思路:
- 我们已经知道了所有时刻的股票价格。
- 只需判断如果明天的价格比今天高,则表示需要交易。即今天买入,明天卖出。
- 遍历数组,如果n+1天的价格大于第n天,利润就加上两者价格差。
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let result = 0;
for (let index = 0; index < prices.length - 1; index++) {
// 计算当前价格与下一天价格的差值
const dif = prices[index + 1] - prices[index];
// 如果下一天的股票价格更高,则表示需要进行交易
if (dif > 0) {
// 保存赚取的差价
result += dif;
}
}
return result;
};