标签:
题目来源:
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
[LeetCode]题解(python):123-Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/chruny/p/5302870.html