Skip to content

Commit e6d1631

Browse files
committed
Best Time to Buy and Sell Stock
1 parent c359aee commit e6d1631

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function maxProfit(prices: number[]): number {
2+
let minPrice = Number.MAX_SAFE_INTEGER;
3+
let maxProfit = 0;
4+
5+
for (let i = 0; i < prices.length; i++) {
6+
if (prices[i] < minPrice) {
7+
minPrice = prices[i];
8+
}
9+
10+
const potentialProfit = prices[i] - minPrice;
11+
12+
if (maxProfit < potentialProfit) {
13+
maxProfit = potentialProfit;
14+
}
15+
}
16+
17+
return maxProfit;
18+
}

0 commit comments

Comments
 (0)