Best Time to Buy and Sell Stock III LeetCode solution in Java
1class Solution {2public int maxProfit(int[] prices) {34int n = prices.length;5int maxSellProfit = 0;6int min = prices[0];7int[] maxSellArr = new int[n];8int i = 1;910while (i < n) {11if (prices[i] < min) {12min = prices[i];13}14maxSellArr[i] = Math.max(maxSellArr[i - 1], prices[i] - min);1516i++;17}18int[] maxBuyArr = new int[n];19int j = n - 2;20int max = prices[n - 1];21while (j >= 0) {22if (prices[j] > max) {23max = prices[j];24}25maxBuyArr[j] = Math.max(maxBuyArr[j + 1], max - prices[j]);2627j--;28}29int maxProfitTwoTrans = 0;30for (int k = 0; k < n; k++) {31maxProfitTwoTrans = Math.max(maxProfitTwoTrans, maxBuyArr[k] + maxSellArr[k]);32}33return maxProfitTwoTrans;34}35}