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

Posted Ry_Chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):123-Best Time to Buy and Sell Stock III相关的知识,希望对你有一定的参考价值。

题目来源:

  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的主要内容,如果未能解决你的问题,请参考以下文章

力扣(LeetCode)整数反转 个人题解

LeetCodePython题解Reverse Integer

[LeetCode]题解(python):100 Same Tree

力扣(LeetCode)加一 个人题解

[LeetCode]题解(python):112 Path Sum

[LeetCode]题解(python):133-Clone Graph