-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimeToSellStockII.java
More file actions
49 lines (36 loc) · 1.54 KB
/
BestTimeToSellStockII.java
File metadata and controls
49 lines (36 loc) · 1.54 KB
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
public class BestTimeToSellStockII {
public int maxProfit(int[] prices) {
int maxPrice = 0;
int rightPoint = 1;
int leftPoint = 0;
while (rightPoint < prices.length) {
if (prices[leftPoint] <= prices[rightPoint]) {
int currentProfit = prices[rightPoint] - prices[leftPoint];
maxPrice = Math.max(maxPrice, currentProfit);
int leftSecondIndex = rightPoint ;
if (leftSecondIndex < prices.length - 1) {
int rightSecondIndex = leftSecondIndex + 1;
int secondMaxPrice = 0;
while (rightSecondIndex < prices.length) {
if (prices[leftSecondIndex] <= prices[rightSecondIndex]) {
secondMaxPrice = Math.max(secondMaxPrice, prices[rightSecondIndex] - prices[leftSecondIndex]);
} else {
leftSecondIndex = rightSecondIndex;
}
rightSecondIndex++;
}
maxPrice = Math.max(maxPrice, currentProfit + secondMaxPrice);
}
} else {
leftPoint = rightPoint;
}
rightPoint++;
}
return maxPrice;
}
public static void main(String[] args) {
BestTimeToSellStockII bestTimeToSellStockII = new BestTimeToSellStockII();
int[] price = {3,3,5,0,0,3,1,4};
System.out.println(bestTimeToSellStockII.maxProfit(price));
}
}