Skip to content

Commit 34258fa

Browse files
committed
solve best-time-to-buy-and-sell-stock
1 parent 2200f1d commit 34258fa

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function maxProfit(prices: number[]): number {
2+
let minPrice = Number.MAX_SAFE_INTEGER;
3+
let maxProfit = 0;
4+
5+
for (let p of prices) {
6+
if (minPrice >= p) {
7+
minPrice = p;
8+
continue;
9+
} else {
10+
let profit = p - minPrice;
11+
if (profit > maxProfit) maxProfit = profit;
12+
}
13+
}
14+
return maxProfit;
15+
}
16+
17+
function maxProfit(prices: number[]): number {
18+
let minPrice = Infinity;
19+
let maxProfit = 0;
20+
21+
for (let p of prices) {
22+
minPrice = Math.min(minPrice, p);
23+
maxProfit = Math.max(maxProfit, p - minPrice);
24+
}
25+
return maxProfit;
26+
}

0 commit comments

Comments
 (0)