-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestStockSell2.java
More file actions
38 lines (31 loc) · 806 Bytes
/
Copy pathBestStockSell2.java
File metadata and controls
38 lines (31 loc) · 806 Bytes
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
package techQuestions;
public class BestStockSell2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] prices = {7,1,5,3,6,4};
System.out.println(bestStockSell2(prices));
}
public static int bestStockSell2(int[] prices) {
int maxProfit = 0;
int peak = prices[0];
int valley = prices[0];
int i = 0;
while (i < prices.length - 1) {
// discovering valley
while (i < prices.length - 1 && prices[i] >= prices[i+1]) {
i++;
}
valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i+1]) {
i++;
}
peak = prices[i];
maxProfit = maxProfit + (peak - valley);
}
return maxProfit;
// return calculatePrices(arr, 0);
}
public static int calculatePrices(int[] arr, int startIndex) {
return 0;
}
}