Best Time to Buy and Sell Stock III

Say you have an array for which the i-th 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).

Solution:

  1. public class Solution {
  2. public int maxProfit(int[] prices) {
  3. if (prices == null || prices.length == 0) {
  4. return 0;
  5. }
  6. int n = prices.length;
  7. int profit = 0;
  8. // scan from left
  9. // left[i] keeps the max profit from 0 to i
  10. int[] left = new int[n];
  11. int min = prices[0];
  12. for (int i = 1; i < n; i++) {
  13. left[i] = Math.max(left[i - 1], prices[i] - min);
  14. min = Math.min(min, prices[i]);
  15. }
  16. // scan from right
  17. // right[i] keeps the max profit from i to n - 1
  18. int[] right = new int[n];
  19. int max = prices[n - 1];
  20. for (int i = n - 2; i >= 0; i--) {
  21. right[i] = Math.max(right[i + 1], max - prices[i]);
  22. max = Math.max(max, prices[i]);
  23. profit = Math.max(profit, left[i] + right[i]);
  24. }
  25. return profit;
  26. }
  27. }

Time complexity: O(n)