forked from v100901/hackoctoberfest2020__
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStockandSell.java
73 lines (56 loc) · 1.89 KB
/
StockandSell.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.ArrayList;
// Solution structure
class Interval {
int buy, sell;
}
class StockBuySell {
// This function finds the buy sell schedule for maximum profit
void stockBuySell(int price[], int n)
{
// Prices must be given for at least two days
if (n == 1)
return;
int count = 0;
// solution array
ArrayList<Interval> sol = new ArrayList<Interval>();
// Traverse through given price array
int i = 0;
while (i < n - 1) {
while ((i < n - 1) && (price[i + 1] <= price[i]))
i++;
if (i == n - 1)
break;
Interval e = new Interval();
e.buy = i++;
// Store the index of minima
// Find Local Maxima. Note that the limit is (n-1) as we are
// comparing to previous element
while ((i < n) && (price[i] >= price[i - 1]))
i++;
// Store the index of maxima
e.sell = i - 1;
sol.add(e);
// Increment number of buy/sell
count++;
}
// print solution
if (count == 0)
System.out.println("There is no day when buying the stock "
+ "will make profit");
else
for (int j = 0; j < count; j++)
System.out.println("Buy on day: " + sol.get(j).buy
+ " "
+ "Sell on day : " + sol.get(j).sell);
return;
}
public static void main(String args[])
{
StockBuySell stock = new StockBuySell();
// stock prices on consecutive days
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
int n = price.length;
// function call
stock.stockBuySell(price, n);
}
}