leetcode-javscript-买卖股票的最佳时机 II

2019-10-22  本文已影响0人  一书文集

贪心算法

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
}
上一篇下一篇

猜你喜欢

热点阅读