贪心算法
var maxProfit = function(prices) {
let maxprofit = 0;
for(let i = 1; i < prices.length; i++ ) {
if(prices[i] > prices[i-1]) //将没买到的买回来
maxprofit += (prices[i] - prices[i - 1])
}
return maxprofit
}
谷峰法
var maxProfit = function(prices) {
let valley = prices[0]
let peak = prices[0]
let maxprofit = 0;
let i =0;
while(i < prices.length -1) {
while(i < prices.length - 1 && prices[i] >= prices[i+1]) //大于后面 后面后面设置为谷底
i++
valley = prices[i]
while(i < prices.length - 1 && prices[i] <= prices[i+1])
i++
peak = prices[i]
maxprofit += (peak - valley)
}
return maxprofit
}
网友评论