首页 > 其他 > 详细

LeetCode #122. Best Time to Buy and Sell Stock II

时间:2020-10-22 12:11:40      阅读:24      评论:0      收藏:0      [点我收藏+]

题目

122. Best Time to Buy and Sell Stock II


解题方法

这道题有两种解决办法,第一种是找到峰值和谷值并计算最大利润,第二种是用了累加的思想,对峰谷值方法进行了简化。

峰谷值法:遍历数组找先到第一个谷值,再找到第一个峰值,计算差值加到最大利润中,然后再从当前位置找下一个谷值和峰值,直到结束。

改进版:遍历数组,如果当前位置的价格比前一位高,就把差价加到总利润中,直到结束。


代码

峰谷值法

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxprofit = 0
        i = 0
        
        while i < len(prices) - 1:
            while i < len(prices) - 1 and prices[i] >= prices[i+1]:
                i += 1
            valley = prices[i]
            while i < len(prices) - 1 and prices[i] <= prices[i+1]:
                i += 1
            peak = prices[i]
            maxprofit += peak - valley
        
        return maxprofit

改进

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxprofit = 0
        
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                maxprofit += prices[i] - prices[i-1]
        
        return maxprofit

LeetCode #122. Best Time to Buy and Sell Stock II

原文:https://www.cnblogs.com/RatsCommander/p/13857038.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!