码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):123-Best Time to Buy and Sell Stock III

时间:2016-03-21 18:00:34      阅读:557      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

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


 

题意分析:

  和上题类似,array[i]代表第i天物品价格,如果只能交易2次。问最大利润。


 

题目思路:

  这是一个动态规划问题。不难想到把整个数组拆成两部分。那么用两个数组First,second分别array[:i]和array[i:]的最大利润。那么答案就等于max(First[i] + second[i + 1])。


 

代码(python):

  

技术分享
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        size = len(prices)
        if size == 0: return 0
        first,second = [0 for i in range(size)],[0 for i in range(size+1)]
        minp = prices[0]
        for i in range(size):
            if prices[i] <= minp:
                minp = prices[i];first[i] = first[i - 1]
            first[i] = max(prices[i] - minp,first[i-1])
        maxp = prices[size-1]
        j = size - 1
        while j >= 0:
            if prices[j] >= maxp:
                maxp = prices[j]
            second[j] = max(second[j+1],maxp - prices[j])
            j -= 1
        ans = 0
        for i in range(size):
            ans = max(ans,first[i]+second[i+1])
        return ans
View Code

 

[LeetCode]题解(python):123-Best Time to Buy and Sell Stock III

标签:

原文地址:http://www.cnblogs.com/chruny/p/5302870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!