美文网首页
leetcode-javscript-买卖股票的最佳时机 II

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

作者: 一书文集 | 来源:发表于2019-10-22 07:56 被阅读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
    }
    

    相关文章

      网友评论

          本文标题:leetcode-javscript-买卖股票的最佳时机 II

          本文链接:https://www.haomeiwen.com/subject/wfirmctx.html