题目如下:
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).
分析如下:
见这里
我的代码:
第一次错误的代码如下,错在没有记录历史的最大值信息。
/*
Input: [2,1,2,0,1]
Output: 1
Expected: 2
*/
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) {
return 0;
}
int[] leftProfit = new int [prices.length];
int[] rightProfit = new int [prices.length];
int minPrice = prices[0];
for (int i = 0; i < prices.length; ++i) {
if (prices[i] < minPrice) {
minPrice = prices[i];
}
leftProfit[i]= prices[i] - minPrice;
}
int maxPrice = prices[prices.length - 1];
for (int i = prices.length - 1; i >= 0; --i) {
if (prices[i] > maxPrice) {
maxPrice = prices[i];
}
rightProfit[i] = maxPrice - prices[i];
}
// int final = 0 // java中算错误,是保留的关键字
int finalResult = 0;
for (int i = 0; i < prices.length; ++i) {
int result = leftProfit[i] + rightProfit[i];
if (result > finalResult) {
finalResult = result;
}
}
return finalResult;
}
}
修改后如下,
/*
Input: [2,1,2,0,1]
Output: 1
Expected: 2
*/
//350ms
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) {
return 0;
}
int[] leftProfit = new int [prices.length];
int[] rightProfit = new int [prices.length];
int minPrice = prices[0];
for (int i = 0; i < prices.length; ++i) {
if (prices[i] < minPrice) {
minPrice = prices[i];
}
leftProfit[i]= prices[i] - minPrice;
// BUG1: leftProfit是记录从index = 0 ~ index = i中的所有可能情况的最大值,
// 即,index = i时候的leftProit由之前的index算出来,而不是当前的index算出来。
// 所以这里还要更新leftProfit数组。
if (i != 0 && leftProfit[i] < leftProfit[i - 1]) {
leftProfit[i] = leftProfit[i - 1];
}
}
int maxPrice = prices[prices.length - 1];
for (int i = prices.length - 1; i >= 0; --i) {
if (prices[i] > maxPrice) {
maxPrice = prices[i];
}
rightProfit[i] = maxPrice - prices[i];
// BUG2: 同BUG1
if (i != prices.length - 1 && rightProfit[i] < rightProfit[i + 1] ) {
rightProfit[i] = rightProfit[i + 1];
}
}
// int final = 0 // java中使用final作为变量名字是错误的,这是保留的关键字
int finalResult = 0;
for (int i = 0; i < prices.length; ++i) {
int result = leftProfit[i] + rightProfit[i];
if (result > finalResult) {
finalResult = result;
}
}
return finalResult;
}
}