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).
Hide Similar Problems
分析:
最多买卖两次,那就把元素组分成两段,分别求出两段的最大利益,然后相加,于是得到动态规划解法(类似于求出数组中除去自身元素外的其他所有元素的乘积):
先从前往后,求出第0天到第i天买卖一次能获得的最大利益,记入forward[i];
再从后往前,求出第i天到n-1 天买卖一次能获得的最大利益,记入backward[i];
然后两次买卖的最大利益 max_profi = max{forward[i] + backward[i]},其中i取值[0,n-1]
12ms//
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
int n = prices.size();
if(n < 2)
return 0;
if( n == 2)
return prices[1]> prices[0]? prices[1] - prices[0]:0;
vector<int> forward(n,0); //forward[i]表示从第0天到第i天买卖一次能获得的最大利益
vector<int> backward(n,0); //backward[i]表示从第i天到n-1天买卖一次能获得的最大利益
int min_p = prices[0];
for(int i = 1; i < n; i++){ //从前往后计算forward
if(prices[i] < min_p)
min_p = prices[i];
int t = prices[i] - min_p;
forward[i] = max(t,forward[i-1]);
}
int max_p = prices[n-1];
for(int i = n-2; i >= 0; i--){ //从后往前计算backward
if(prices[i] > max_p)
max_p = prices[i];
int t = max_p - prices[i];
backward[i] = max(t,backward[i+1]);
}
int max_profi = 0;
for(int i = 0; i < n - 1; i++){ //求出两段和最大值
int t = forward[i] + backward[i];
max_profi = max(max_profi , t);
}
return max_profi;
}
};