Skip to content

Commit 1ad5d21

Browse files
committed
best time to buy and sell stock solution
1 parent d878003 commit 1ad5d21

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function maxProfit(prices: number[]): number {
2+
let minPrice = Infinity;
3+
let maxProfit = 0;
4+
5+
for (const price of prices) {
6+
if (price < minPrice) {
7+
minPrice = price;
8+
} else {
9+
maxProfit = Math.max(maxProfit, price - minPrice);
10+
}
11+
}
12+
13+
return maxProfit;
14+
}

0 commit comments

Comments
 (0)