美文网首页
36.LeetCode122. 买卖股票的最佳时机II

36.LeetCode122. 买卖股票的最佳时机II

作者: 月牙眼的楼下小黑 | 来源:发表于2018-10-03 10:46 被阅读11次
  • 标签: 贪心 数组
  • 难度: 简单

  • 题目描述
  • 我的解法

将数据进行可视化后发现: 买入点是谷点(V),卖出点是峰点(P),一对相邻的峰点和鼓点对应一次交易。每次交易获利等于峰点和谷点的差值。只要依次找到 成对 的谷点和峰点,且 谷点在前,峰点在后, 累加高度差即可求得最大利润。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit = 0
        if not prices:
            return 0
        i = 0
        while(i < len(prices) - 1):
            if (i < len(prices) - 1 and prices[i] >= prices[i + 1]):
                i += 1
            v = prices[i]
            if(i < len(prices) - 1 and prices[i] <= prices[i + 1]):
                i += 1
            p = prices[i]
            profit += p - v
        return profit                        
  • 其他解法

暂略。

相关文章

网友评论

      本文标题:36.LeetCode122. 买卖股票的最佳时机II

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