Skip to content

Commit d35c23f

Browse files
committed
Feat: 121. Best Time to Buy and Sell Stock
1 parent 92359ca commit d35c23f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
2+
// T.C: O(N)
3+
// S.C: O(1)
4+
function maxProfit(prices: number[]): number {
5+
let min = prices[0];
6+
let max = prices[0];
7+
let candidate = prices[0];
8+
9+
for (let i = 1; i < prices.length; i++) {
10+
if (prices[i] < candidate) {
11+
candidate = prices[i];
12+
} else if (prices[i] - candidate > max - min) {
13+
min = candidate;
14+
max = prices[i];
15+
}
16+
}
17+
18+
return max - min;
19+
}

0 commit comments

Comments
 (0)