Skip to content

Commit 9a4e19b

Browse files
author
highflyer910
committed
Max Stock Profit
1 parent ca7bfef commit 9a4e19b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

maxstockprofit.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function maxStockProfit (pricesArr) {
2+
var maxProfit = -1;
3+
var buyPrice = 0;
4+
var sellPrice = 0;
5+
6+
var changeBuyPrice = true;
7+
8+
for (var 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+
}
15+
else {
16+
var tempProfit = sellPrice - buyPrice;
17+
if (tempProfit > maxProfit) maxProfit = tempProfit;
18+
changeBuyPrice = false;
19+
}
20+
}
21+
22+
return maxProfit;
23+
}

0 commit comments

Comments
 (0)