Best Time to Buy and Sell Stock III LeetCode solution in Java

1
class Solution {
2
public int maxProfit(int[] prices) {
3

4
int n = prices.length;
5
int maxSellProfit = 0;
6
int min = prices[0];
7
int[] maxSellArr = new int[n];
8
int i = 1;
9

10
while (i < n) {
11
if (prices[i] < min) {
12
min = prices[i];
13
}
14
maxSellArr[i] = Math.max(maxSellArr[i - 1], prices[i] - min);
15

16
i++;
17
}
18
int[] maxBuyArr = new int[n];
19
int j = n - 2;
20
int max = prices[n - 1];
21
while (j >= 0) {
22
if (prices[j] > max) {
23
max = prices[j];
24
}
25
maxBuyArr[j] = Math.max(maxBuyArr[j + 1], max - prices[j]);
26

27
j--;
28
}
29
int maxProfitTwoTrans = 0;
30
for (int k = 0; k < n; k++) {
31
maxProfitTwoTrans = Math.max(maxProfitTwoTrans, maxBuyArr[k] + maxSellArr[k]);
32
}
33
return maxProfitTwoTrans;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0