-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-16 Best Time to Buy and Sell Stock III
53 lines (48 loc) · 1.33 KB
/
Day-16 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
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];
int leftmin=prices[0];
for(int i=1;i<n;i++){
if(prices[i]<leftmin){
leftmin=prices[i];
left[i]=left[i-1];
}
else{
left[i]=Math.max(left[i-1],prices[i]-leftmin);
}
}
int rightmax=prices[n-1];
for(int i=n-2;i>=0;i--){
if(prices[i]>rightmax){
rightmax=prices[i];
right[i]=right[i+1];
}
else{
right[i]=Math.max(right[i+1],rightmax-prices[i]);
}
}
int max=0;
for(int i=0;i<n;i++){
max=Math.max(max,left[i]+right[i]);
}
return max;
}
}
class Solution {
public int maxProfit(int[] prices) {
int t1Cost = Integer.MAX_VALUE,
t2Cost = Integer.MAX_VALUE;
int t1Profit = 0,
t2Profit = 0;
for (int price : prices) {
t1Cost = Math.min(t1Cost, price);
t1Profit = Math.max(t1Profit, price - t1Cost);
t2Cost = Math.min(t2Cost, price - t1Profit);
t2Profit = Math.max(t2Profit, price - t2Cost);
}
return t2Profit;
}
}