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)