Skip to content

Commit c9e39db

Browse files
committed
add solution : 121. Best Time to Buy and Sell Stock
1 parent 8df437d commit c9e39db

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
*
3+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
4+
* - max profit์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋กœ O(n)์œผ๋กœ ํ’€๊ธฐ
5+
* - ํ˜„์žฌ ๊ฐ€๊ฒฉ์—์„œ ๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€๊ฒฉ์„ ๋บ€ ๊ฐ’์„ max profit์œผ๋กœ ์„ค์ •
6+
*
7+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
8+
* - n์€ prices ๊ธธ์ด, ์š”์†Œ 1ํšŒ ์ˆœํšŒํ•˜๋‹ˆ๊นŒ O(n)
9+
*
10+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
11+
* - ๋ณ€์ˆ˜ 2๊ฐœ ์‚ฌ์šฉํ•˜๋‹ˆ๊นŒ O(1)
12+
*/
13+
14+
function maxProfit(prices: number[]): number {
15+
let minPrice = prices[0],
16+
maxProfit = 0;
17+
18+
for (const price of prices) {
19+
minPrice = Math.min(price, minPrice);
20+
maxProfit = Math.max(maxProfit, price - minPrice);
21+
}
22+
23+
return maxProfit;
24+
}

0 commit comments

Comments
ย (0)