- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathStockBuyAndSell.java
50 lines (36 loc) Β· 1.14 KB
/
StockBuyAndSell.java
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
packagegfg.Arrays;
publicclassStockBuyAndSell {
publicstaticvoidmain(String[] args) {
int[] price = { 1, 5, 3, 8, 12 };
intstart = 0;
intend = price.length - 1;
System.out.println("Max profit is: " + stockMaxProfit(price, start, end));
int[] price2 = { 30, 20, 10 };
end = price2.length - 1;
System.out.println("Max profit is: " + stockMaxProfit(price2, start, end));
int[] price3 = { 10, 20, 30 };
end = price3.length - 1;
System.out.println("Max profit is: " + stockMaxProfit(price3, start, end));
int[] price4 = { 1, 5, 3, 1, 2, 8 };
end = price4.length - 1;
System.out.println("Max profit is: " + stockMaxProfit(price4, start, end));
}
publicstaticintstockMaxProfit(int[] price, intstart, intend) {
if (end <= start) {
return0;
}
intprofit = 0;
for (inti = start; i < end; i++) {
for (intj = i + 1; j <= end; j++) {
if (price[j] > price[i]) {
intcurrentProfit = (price[j] - price[i]) + stockMaxProfit(price, start, i - 1)
+ stockMaxProfit(price, j + 1, end);
if (currentProfit > profit) {
profit = currentProfit;
}
}
}
}
returnprofit;
}
}