Skip to content

Commit f1b408d

Browse files
authored
Merge pull request #458 from seona926/main
[Sophia] Week5 Solution
2 parents 6411e48 + c973a58 commit f1b408d

File tree

1 file changed

+23
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)