-
Notifications
You must be signed in to change notification settings - Fork 0
/
121.js
31 lines (29 loc) · 809 Bytes
/
121.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
// One pass
var maxProfit = function(prices) {
let lowestPrice=Number.MAX_VALUE,maxProfit=0;
for(let i=0;i<prices.length;i++){
if(prices[i]<lowestPrice){
lowestPrice = prices[i];
}else{
let profit = prices[i]-lowestPrice;
if(profit>maxProfit){
maxProfit = profit;
}
}
}
return maxProfit;
};
// Kadane's algorithm
var maxProfit = function(prices) {
let diffs=prices.map((price,id)=>{
if(id===0)return 0;
else return price-prices[id-1];
})
let maxProfit=0;
let maxSoFar=0;
for(let i=0;i<diffs.length;i++){
maxProfit=diffs[i]>maxProfit+diffs[i]?diffs[i]:maxProfit+diffs[i];
maxSoFar=(maxProfit>maxSoFar)?maxProfit:maxSoFar;
}
return maxSoFar;
};