122. Best Time to Buy and Sell Stock II [medium] (Python)

题目链接

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

题目原文

Say you have an array for which the ith element is the price of a given stock on day i <script type="math/tex" id="MathJax-Element-2">i</script>.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路方法

思路一

额。。。虽说这题是贪心算法的应用,不过稍微还是简单了点。就怕想的太复杂,实际上只要能挣钱就买入卖出即可。

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        res = 0
        for i in xrange(1, len(prices)):
            if prices[i-1] < prices[i]:
                res += prices[i] - prices[i-1]
        return res

思路二

按照对题目的理解,对于类似[1,2,3,0]这样的序列,最正确的做法是“1元买入3元卖出”。而上面的解法感觉像是“1元买入2元卖出,2元买入3元卖出”,当然,结果是对的,而且其实上面的解法相当于代码优化。比较繁一点的解法是“先找局部最小,再找局部最大”这样的循环,代码如下:

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        res = 0
        i = 0
        while i < len(prices):
            while i < len(prices)-1 and prices[i+1] <= prices[i]:
                i += 1
            j = i + 1
            while j < len(prices)-1 and prices[j+1] >= prices[j]:
                j += 1
            res += prices[j] - prices[i] if j < len(prices) else 0
            i = j + 1
        return res

PS: 写错了或者写的不清楚请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52072136

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值