8000 Create 123. Best Time to Buy and Sell Stock III · SreeHarsha070/Leetcode-Challenge@da6c61b · GitHub
[go: up one dir, main page]

Skip to content

Commit da6c61b

Browse files
authored
Create 123. Best Time to Buy and Sell Stock III
1 parent 698c817 commit da6c61b

File tree

1 file changed

+64
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)
0