forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbesttime2buyandsell2.java
More file actions
executable file
·44 lines (42 loc) · 1.16 KB
/
besttime2buyandsell2.java
File metadata and controls
executable file
·44 lines (42 loc) · 1.16 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
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
boolean increasing;
int lowP;
int highP;
if(prices==null || prices.length<2){
return 0;
}
if(prices[0]<prices[1]){
lowP = prices[0];
highP = prices[1];
increasing = true;
}
else{
lowP = prices[1];
highP = prices[0];
increasing = false;
}
int Profit = 0;
for(int i=2;i<prices.length;i++){
if(prices[i]>prices[i-1]){
if(increasing == false){
lowP = prices[i-1];
increasing = true;
}
}else{
if(increasing == true ){
highP = prices[i-1];
Profit += (highP-lowP);
increasing = false;
}
}
}
if(increasing == true){
highP = prices[prices.length-1];
Profit += highP-lowP;
}
return Profit;
}
}