Skip to content

Commit 514f317

Browse files
committed
Add week 5 solutions: best-time-to-buy-and-sell-stock
1 parent 92359ca commit 514f317

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
function maxProfit(prices: number[]): number {
8+
let maxProfit = 0;
9+
let [minPrice] = prices;
10+
11+
for (let price of prices) {
12+
maxProfit = Math.max(maxProfit, price - minPrice);
13+
minPrice = Math.min(minPrice, price);
14+
}
15+
16+
return maxProfit;
17+
};

0 commit comments

Comments
 (0)