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).
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if(prices.length == 0){
return 0;
}
int result = Integer.MIN_VALUE;
int[] profits = new int[prices.length];
int min = Integer.MAX_VALUE, maxBeforeI = Integer.MIN_VALUE;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
}
if (prices[i] - min > maxBeforeI) {
maxBeforeI = prices[i] - min;
}
profits[i] = maxBeforeI;
}
int max = Integer.MIN_VALUE;
for (int i = prices.length - 1; i >= 0; i--) {
if (prices[i] > max) {
max = prices[i];
} int profit = max - prices[i]; if (profit + profits[i] > result) {
result = profit + profits[i];
}
}
return result;
}
}
m transactions solution not understand
http://discuss.leetcode.com/questions/287/best-time-to-buy-and-sell-stock-iii