Say you have an array for which the i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Solution

动态规划法:用两个数组,数组f1[i]表示在[0, i]范围内进行一次买入卖出的最大收益,数组f2[i]表示在[i, n-1]范围内进行一次买入卖出的最大收益,则总的最大收益为max(f1[i]+f2[i]),数组f1、f2的求法参考题目121

python

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         length = len(prices)
 8         if length <= 1:
 9             return 0
10 
11         f1 = []
12         f2 = []
13         min_price = prices[0]
14         f1.append(0)
15         for i in range(1, length):
16             min_price = min(min_price, prices[i])
17             f1.append(max(f1[i-1], prices[i]-min_price))
18 
19         # reverse the prices list to iterate them from behind
20         prices_re = prices
21         prices_re.reverse()
22         f2.append(0)
23         max_price = prices_re[0]
24         for i in range(1, length):
25             max_price = max(max_price, prices_re[i])
26             f2.append(max(f2[i-1], max_price-prices_re[i]))
27 
28         f2.reverse()
29         max_profit = 0
30         for i in range(length):
31             max_profit = max(max_profit, f1[i]+f2[i])
32 
33         return max_profit
View Code

相关文章:

  • 2022-12-23
  • 2021-07-28
  • 2021-09-27
  • 2022-12-23
  • 2021-06-15
猜你喜欢
  • 2021-06-02
  • 2022-01-08
  • 2021-06-22
  • 2022-02-15
  • 2021-08-24
  • 2021-09-09
  • 2022-12-23
相关资源
相似解决方案