forked from shams-nahid/Algorithms-In-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxStockPrice.js
More file actions
29 lines (23 loc) · 732 Bytes
/
Copy pathmaxStockPrice.js
File metadata and controls
29 lines (23 loc) · 732 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
let maxStockProfit = (priceArray, cb) => {
let maxProfit = -1;
let buyPrice, sellPrice, changeOfBuyPrice = true;
for (let index=0; index< priceArray.length - 1; index++) {
if (changeOfBuyPrice) {
buyPrice = priceArray[index];
}
sellPrice = priceArray[index + 1];
if (sellPrice < buyPrice) {
changeOfBuyPrice = true;
} else {
maxProfit = ((sellPrice - buyPrice) > maxProfit) ? (sellPrice - buyPrice) : maxProfit;
changeOfBuyPrice = false;
}
}
return cb(null, maxProfit);
};
maxStockProfit([32, 46, 26, 38, 40, 48, 42], (err, maxProfit) => {
if (err) {
} else {
console.log(maxProfit);
}
});