-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path122.js
41 lines (38 loc) · 769 Bytes
/
122.js
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
//Peak-valley approach
var maxProfit = function(prices) {
let buy=[];
let i=0;
while(i<prices.length){
let start = i;
while(prices[i]<prices[i+1]){
i++;
}
if(start!==i){
buy.push([start,i]);
}else{
i++;
}
}
let res=0;
buy.forEach((day)=>{
res+=prices[day[1]]-prices[day[0]];
})
return res;
};
//simple one pass
var maxProfit = function(prices) {
let res=0;
let end=0;
while(end<prices.length){
let start = end;
while(prices[end]<prices[end+1]){
end++;
}
if(start!==end){
res+=prices[end]-prices[start];
}else{
end++;
}
}
return res;
};