123. Best Time to Buy and Sell Stock III
Last updated
Last updated
/**
* Time complexity : O(N) where N is the length of the input sequence,
* since we have two iterations of length N.
* Space complexity : O(N) for the two arrays that we keep in the algorithm.
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1) return 0;
int n = prices.length;
int[] leftProfits = new int[n];
int[] rightProfits = new int[n+1];
int leftMin = Integer.MAX_VALUE;
int rightMax = Integer.MIN_VALUE;
for(int l = 0; l < n; l++) {
leftMin = Math.min(leftMin, prices[l]);
leftProfits[l] = Math.max(leftProfits[l], prices[l]-leftMin);
int r = n-1-l;
rightMax = Math.max(rightMax, prices[r]);
rightProfits[r] = Math.max(rightProfits[r+1], rightMax-prices[r]);
}
int maxProfit = 0;
for(int i = 0; i < n; i++) {
maxProfit = Math.max(maxProfit, leftProfits[i]+rightProfits[i]);
}
return maxProfit;
}
}/**
* Time complexity : O(N), where N is the length of the input sequence.
* Space complexity : O(1), only constant memory is required, which is
* invariant from the input sequence.
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1) return 0;
int t1Cost = Integer.MAX_VALUE,
t2Cost = Integer.MAX_VALUE;
int t1Profit = 0,
t2Profit = 0;
for (int price : prices) {
// the maximum profit if only one transaction is allowed
t1Cost = Math.min(t1Cost, price);
t1Profit = Math.max(t1Profit, price - t1Cost);
// reinvest the gained profit in the second transaction
t2Cost = Math.min(t2Cost, price - t1Profit);
t2Profit = Math.max(t2Profit, price - t2Cost);
}
return t2Profit;
}
}