美文网首页
Leetcode-122题:Best Time to Buy a

Leetcode-122题:Best Time to Buy a

作者: 八刀一闪 | 来源:发表于2016-09-26 20:47 被阅读18次

    题目

    Say you have an array for which the ith element is the price of a given stock on day i.

    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).

    思路

    股票涨至局部最高点再卖。将价格分为一个个的递增区间,对于每个区间,区间首买入区间尾卖出。
    [1,2,3,2,4],3-1 + 4-2 > 4-1

    代码

    class Solution(object):
    
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            if prices==None or len(prices)<=1:
                return 0
            profit = 0
            l = 0
            while l < len(prices):
                r = l
                while r+1<len(prices) and prices[r+1]>prices[r]:
                    r += 1
                if prices[r] > prices[l]:
                    profit = profit + prices[r] - prices[l]
                    l = r
                else:
                    l += 1
            return profit
    

    相关文章

      网友评论

          本文标题:Leetcode-122题:Best Time to Buy a

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