题目:
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).
题解:
注意Note的意思。虽然你不能engage in multiple transactions at the same time,但是你可以在同一天的同一个价位先卖出,再立刻买入。由此可以把两次交易分为[0,…,i]中的一次交易和[i,…,n-1]中的一次交易。
分别用动态规划求[0,…,i]和[i,…,n-1]获利的最大值,注意求[i,…,n-1]的最大获利时为逆向动态规划,即n-1天买,n-1天卖的最大利润,[n-2,n-1]最大利润,[n-3,...,n-1]最大利润,一次类推。
动态规划的递推式为:
正向: 记录当前prices_min, profit[i] = max(profit[i-1], prices[i] - prices_min)
逆向: 记录当前prices_max, profit[i] = max(profit[i+1], prices_max - prices[i])
c++版:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() <= 1)
return 0;
int low = prices[0];
vector<int> left(prices.size(), 0);
for(int i = 1; i < prices.size(); i++) {
if(prices[i] < low)
low = prices[i];
left[i] = max(left[i-1], prices[i] - low);
}
int high = prices[prices.size()-1];
vector<int> right(prices.size(), 0);
for(int i = prices.size()-2; i >= 0; i--) {
if(prices[i] > high)
high = prices[i];
right[i] = max(right[i+1], high-prices[i]);
}
int gain = 0;
for(int i = 0; i < prices.size(); i++) {
if( left[i] + right[i] > gain)
gain = left[i] + right[i];
}
return gain;
}
};
Java版:
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int low = prices[0], high = prices[prices.length-1];
int[] left = new int[prices.length];
int[] right = new int[prices.length];
for(int i = 1; i < prices.length; i++) {
if(prices[i] < low)
low = prices[i];
left[i] = Math.max(left[i-1], prices[i]-low);
if(prices[prices.length-i-1] > high)
high = prices[prices.length-i-1];
right[prices.length-i-1] = Math.max(right[prices.length-i], high-prices[prices.length-i-1]);
}
int gain = 0;
for(int i = 0; i < prices.length; i++) {
if(left[i] + right[i] > gain)
gain = left[i] + right[i];
}
return gain;
}
}
Python版:
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if len(prices) <= 1:
return 0
low = prices[0]
high = prices[len(prices)-1]
left = [0] * len(prices)
right = [0] * len(prices)
for i in range(1, len(prices)):
if prices[i] < low:
low = prices[i]
left[i] = max(left[i-1], prices[i]-low)
if prices[len(prices)-i-1] > high:
high = prices[len(prices)-i-1]
right[len(prices)-i-1] = max(right[len(prices)-i], high-prices[len(prices)-i-1])
gain = 0
for i in range(0, len(prices)):
if left[i] + right[i] > gain:
gain = left[i] + right[i]
return gain