-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuySellStock.java
More file actions
30 lines (27 loc) · 853 Bytes
/
BuySellStock.java
File metadata and controls
30 lines (27 loc) · 853 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
package buySellStock;
public class BuySellStock {
public int maxProfit(int[] prices){
if ( prices.length == 0 ){
return 0;
}
int maxProfit = 0;
int beginIndex = 0;
int endIndex = 0;
for(int i = 1; i < prices.length ; i++){
if(prices[i] < prices[i-1]){
maxProfit += prices[endIndex] - prices[beginIndex];
beginIndex = i;
}
endIndex = i;
}
if(prices[endIndex] > prices[beginIndex]){
maxProfit += prices[endIndex] - prices[beginIndex];
}
return maxProfit;
}
public static void main(String[] args){
BuySellStock t = new BuySellStock();
int[] prices = new int[]{2,1};
System.out.println(t.maxProfit(prices));
}
}