LeetCode - 123. Best Time to Buy and Sell Stock III

 
 

Description

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

cpp

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int length = prices.size();
 5         if (length <= 1)
 6             return 0;
 7 
 8         vector<int> f1(length);
 9         vector<int> f2(length);
10         f1[0] = 0;
11         int min_price = prices[0];
12         // get max_profit1 using positive sequence
13         for (int i=1; i<length; ++i)
14         {
15             min_price = min(min_price, prices[i]);
16             f1[i] = max(f1[i-1], prices[i]-min_price);
17         }
18 
19         // get max_profit2 using inverted sequence
20         f2[length-1] = 0;
21         int max_price = prices[length-1];
22         for (int i=length-2; i>=0; --i)
23         {
24             max_price = max(max_price, prices[i]);
25             f2[i] = max(f2[i+1], max_price-prices[i]);
26         }
27 
28         // generate max_profit for output
29         int max_profit = 0;
30         for (int i=0; i<length; ++i)
31         {
32             max_profit = max(max_profit, f1[i]+f2[i]);
33         }
34 
35         return max_profit;
36     }
37 };
View Code

Reference

 

转载于:https://www.cnblogs.com/gxcdream/p/7512503.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值