初级算法(第二题)
利用贪心算法计算买卖股票的最佳时机II,算出最高收益
给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let totalMoney = 0;
//定义一个收益总数
const day = prices.length;
//如果只有一天的话就没办法看收益了
if(day < 2 || day === null){
return totalMoney;
};
//循环遍历每一天的股价,让后一天的减去前一天的然后的出来的收益和0比较
//小于0的就是赔了大于0的就是赚了然后加到总收益里面
for(let date = 0; date < day-1; date ++){
totalMoney+=Math.max(prices[date+1]-prices[date],0)
}
return totalMoney;
};