Skip to content

Commit 07de45b

Browse files
committedJun 15, 2019
Max stock profit algorithm
1 parent 17f43c7 commit 07de45b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
 

‎Algorithm/maxStockProfit.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function maxStockProfit(pricesArr) {
2+
let maxProfit = -1;
3+
let buyPrice = 0;
4+
let sellPrice = 0;
5+
6+
let changeBuyPrice = true;
7+
8+
for (let i = 0; i < pricesArr.length; i++) {
9+
if (changeBuyPrice) buyPrice = pricesArr[i];
10+
sellPrice = pricesArr[i + 1];
11+
12+
if (sellPrice < buyPrice) {
13+
changeBuyPrice = true;
14+
} else {
15+
let tempProfit = sellPrice - buyPrice;
16+
if (tempProfit > maxProfit) maxProfit = tempProfit;
17+
changeBuyPrice = false;
18+
}
19+
}
20+
21+
return maxProfit;
22+
}
23+
24+
maxStockProfit([10, 18, 4, 5, 9, 6, 16, 12]); // 12

0 commit comments

Comments
 (0)
Please sign in to comment.