Skip to content

Commit fcf70c9

Browse files
committed
add: solve #221 Best Time to Buy And Sell Stock with ts
1 parent 07fa579 commit fcf70c9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* ์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜
3+
* @param {number[]} prices
4+
* @returns {number}
5+
*
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„ : O(n) (n: ์ฃผ์‹ ๊ฐ€๊ฒฉ ๋ฐฐ์—ด์˜ ๊ธธ์ด)
7+
* ๊ณต๊ฐ„ ๋ณต์žก๋„ : 0(1) (์ถ”๊ฐ€ ์ž๋ฃŒ๊ตฌ์กฐ X)
8+
*/
9+
function maxProfit(prices: number[]): number {
10+
let minPrice = 100001; // ์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ์†Œ ๊ฐ€๊ฒฉ
11+
let maxProfit = 0; // ์ตœ๋Œ€ ์ด์ต
12+
13+
for (let price of prices) {
14+
// ์ตœ์†Œ ๊ฐ€๊ฒฉ ๊ฐฑ์‹ 
15+
if (price < minPrice) {
16+
minPrice = price;
17+
}
18+
19+
// ํ˜„์žฌ ๊ฐ€๊ฒฉ์—์„œ ์ตœ์†Œ ๊ฐ€๊ฒฉ์„ ๋บ€ ์ด์ต์ด ์ตœ๋Œ€ ์ด์ต๋ณด๋‹ค ํฌ๋‹ค๋ฉด ๊ฐฑ์‹ 
20+
const potentialProfit = price - minPrice;
21+
if (potentialProfit > maxProfit) {
22+
maxProfit = potentialProfit;
23+
}
24+
}
25+
26+
return maxProfit;
27+
}

0 commit comments

Comments
ย (0)