Skip to content

Commit a48ed05

Browse files
committed
Best Time to Buy and Sell Stock solution
1 parent e3570f2 commit a48ed05

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* ์‹œ๊ฐ„ ๋ณต์žก๋„ O(n)
3+
* ๊ณต๊ฐ„ ๋ณต์žก๋„ O(1)
4+
*
5+
* ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜
6+
* ํ˜„์žฌ๊นŒ์ง€์˜ ์ตœ์ € ๊ฐ€๊ฒฉ์„ ๊ธฐ์–ตํ•˜๊ณ , ๊ทธ ๊ฐ€๊ฒฉ์— ์ƒ€์„ ๋•Œ์˜ ์ด์ต์„ ๊ณ„์† ๊ณ„์‚ฐํ•˜์—ฌ ์ตœ๋Œ€ ์ด์ต์„ ๊ตฌํ•จ
7+
*/
8+
9+
/**
10+
* @param {number[]} prices
11+
* @return {number}
12+
*/
13+
var maxProfit = function (prices) {
14+
let minPrice = prices[0]; // ์ตœ์ € ๊ฐ€๊ฒฉ ์ดˆ๊ธฐํ™” (์ฒซ ๋‚  ๊ฐ€๊ฒฉ)
15+
let maxProfit = 0; // ์ตœ๋Œ€ ์ด์ต ์ดˆ๊ธฐํ™” (์•„์ง ์ด์ต ์—†์Œ)
16+
17+
// ๋‘ ๋ฒˆ์งธ ๋‚ ๋ถ€ํ„ฐ
18+
for (let i = 1; i < prices.length; i++) {
19+
// ํ˜„์žฌ ๊ฐ€๊ฒฉ์ด ์ตœ์ € ๊ฐ€๊ฒฉ๋ณด๋‹ค ๋‚ฎ์œผ๋ฉด ์ตœ์ € ๊ฐ€๊ฒฉ ์—…๋ฐ์ดํŠธ
20+
if (prices[i] < minPrice) {
21+
minPrice = prices[i];
22+
}
23+
// ํ˜„์žฌ ๊ฐ€๋Šฅํ•œ ์ด์ต ๊ณ„์‚ฐ (ํ˜„์žฌ ๊ฐ€๊ฒฉ - ์ตœ์ € ๊ฐ€๊ฒฉ)
24+
const currentProfit = prices[i] - minPrice;
25+
26+
// ์ตœ๋Œ€ ์ด์ต ์—…๋ฐ์ดํŠธ
27+
if (currentProfit > maxProfit) {
28+
maxProfit = currentProfit;
29+
}
30+
}
31+
32+
return maxProfit;
33+
};

0 commit comments

Comments
ย (0)