オリジナルタイトルリンク
タイトル説明
假定你知道某只股票每一天价格的变动。
你最多可以同时持有一只股票。但你最多只能进行两次交易(一次买进和一次卖出记为一次交易。买进和卖出均无手续费)。
请设计一个函数,计算你所能获得的最大收益。
例
输入:
[8,9,3,5,1,3]
输出:
4
リファレンスソリューション
リファレンスブログ
public class Test {
public static void main(String[] args) {
int a[] = {
6, 10, 22, 5, 75, 65, 80 };
System.out.println(maxProfit(a));
}
public static int maxProfit(int[] prices) {
int length = prices.length;
int dp1[] = new int[length];
dp1[0] = 0;
int minPrice = prices[0];
for (int i = 1; i < length; i++) {
dp1[i] = Math.max(prices[i] - minPrice, dp1[i - 1]);
if (prices[i] < minPrice)
minPrice = prices[i];
}
int[] dp2 = new int[length];
dp2[length - 1] = 0;
int maxPrice = prices[length - 1];
for (int i = length - 2; i >= 0; i--) {
dp2[i] = Math.max(maxPrice - prices[i], dp2[i + 1]);
if (prices[i] > maxPrice)
maxPrice = prices[i];
}
int max = 0;
for (int i = 0; i < length; i++) {
max = Math.max(max, dp1[i] + dp2[i]);
}
return max;
}
}