Skip to content

Commit 09b75dc

Browse files
committed
feat: 121. Best Time to Buy and Sell Stock
1 parent d52bb73 commit 09b75dc

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Runtime: 6ms, Memory: 62.30MB
3+
*
4+
* Time Complexity: O(N)
5+
* Space Complexity: O(1)
6+
*/
7+
8+
function maxProfit(prices: number[]): number {
9+
let buyingPrice = prices[0];
10+
let profit = 0;
11+
12+
for (const price of prices) {
13+
buyingPrice = Math.min(price, buyingPrice);
14+
profit = Math.max(profit, price - buyingPrice);
15+
}
16+
17+
return profit;
18+
}
19+
20+
maxProfit([7, 1, 5, 3, 6, 4]);

0 commit comments

Comments
 (0)