Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 07de45b

Browse files
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

Lines changed: 24 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /