Best Time to Buy and Sell Stock III

本文介绍了一种解决股票买卖问题的算法,该算法通过两次交易实现最大利润。通过正向和反向扫描数组,分别计算前半段和后半段的最大收益,最终找到全局最优解。

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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:

将vector分成两部分,用Best Time to Buy and Sell Stock I的方法求得两部分的最大值,然后求和的最大值。要求两部分的最大值需要先正面扫描一遍求得0到i的最大值,在反方向扫描一遍求i到n-1的最大值。

代码:

 1     int maxProfit(vector<int> &prices) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int n = prices.size();
 5         if(n == 0)
 6             return 0;
 7         vector<int> first(n, 0), second(n, 0);
 8         int min = prices[0], maxProfit = 0, max = prices[n-1];
 9         first[0] = 0;
10         for(int i = 1; i < n; i++){
11             if(prices[i] < min){
12                 min = prices[i];
13             }
14             if(prices[i] - min > maxProfit){
15                 maxProfit = prices[i] - min;
16             }
17             first[i] = maxProfit;
18         }
19         second[n-1] = 0;
20         maxProfit = 0;
21         for(int i = n-2; i >= 0; i--){
22             if(prices[i] > max){
23                 max = prices[i];
24             }
25             if(max - prices[i] > maxProfit){
26                 maxProfit = max - prices[i];
27             }
28             second[i] = maxProfit;
29         }
30         maxProfit = first[0] + second[0];
31         for(int i = 1; i < n; i++){
32             if(first[i] + second[i] > maxProfit)
33                 maxProfit = first[i] + second[i];
34         }
35         return maxProfit;
36     }

 

转载于:https://www.cnblogs.com/waruzhi/p/3416252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值