-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path123. Best Time to Buy and Sell Stock III
64 lines (51 loc) · 1.64 KB
/
123. Best Time to Buy and Sell Stock III
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if(n==0) return 0;
int[] left = new int[n];
int[] right = new int[n];
//Bidirectional DP Logic
//Left to right traversal
int min = prices[0];
for(int i = 1; i < n; i++) {
//1. Update Buy price
if(prices[i] < min) min=prices[i];
//2. Calculate current profit
int profit = prices[i]-min;
//3. Fill left array (based on condition)
left[i] = Math.max(left[i-1], profit);
}
//Right to left traversal
int max = prices[n-1];
for(int i = n-2; i>=0; i--) {
//1. Update Sell price
if(prices[i] > max) max=prices[i];
//2. Calculate current profit
int profit = max-prices[i];
//3. Update right array
right[i] = Math.max(right[i+1], profit);
}
int maxProfit = 0;
for(int i = 0; i<n; i++) {
maxProfit = Math.max(maxProfit, left[i]+right[i]);
}
return maxProfit;
}
}
class Solution {
public int maxProfit(int[] prices) {
// c1, c2, p1, p2
int c1 = Integer.MAX_VALUE;
int c2 = Integer.MAX_VALUE;
int p1 = 0;
int p2 = 0;
//Iterate over prices
for(int price : prices) {
c1 = Math.min(c1, price);
p1 = Math.max(p1, price-c1);
c2 = Math.min(c2, price-p1);
p2 = Math.max(p2, price-c2);
}
return p2;
}
}