Skip to content

Commit 0ca4ca3

Browse files
committed
Best Time to Buy and Sell Stock
1 parent d52bb73 commit 0ca4ca3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Time complexity: O(n)
3+
Space complexity: O(1)
4+
5+
문제 μ„€λͺ…:
6+
- μ£Όμ–΄μ§„ λ°°μ—΄ `prices`μ—μ„œ, i <= j인 두 인덱슀 i, j에 λŒ€ν•΄ prices[j] - prices[i]λ₯Ό μ΅œλŒ€ν™”ν•΄μ•Ό ν•©λ‹ˆλ‹€.
7+
- 즉, ν•œ 번의 λ§€μˆ˜μ™€ ν•œ 번의 맀도λ₯Ό 톡해 얻을 수 μžˆλŠ” μ΅œλŒ€ 이읡을 κ³„μ‚°ν•©λ‹ˆλ‹€.
8+
- λ§€μˆ˜λŠ” 맀도보닀 λ°˜λ“œμ‹œ λ¨Όμ € 이루어져야 ν•©λ‹ˆλ‹€.
9+
10+
μ•Œκ³ λ¦¬μ¦˜ μ„€λͺ…:
11+
1. 배열을 μ™Όμͺ½μ—μ„œ 였λ₯Έμͺ½μœΌλ‘œ ν•œ 번 μˆœνšŒν•©λ‹ˆλ‹€.
12+
2. ν˜„μž¬ 주식 가격이 `min_price`보닀 μž‘μœΌλ©΄, `min_price`λ₯Ό κ°±μ‹ ν•©λ‹ˆλ‹€.
13+
- `min_price`λŠ” ν˜„μž¬κΉŒμ§€μ˜ μ΅œμ†Œ 맀수 가격을 μ˜λ―Έν•©λ‹ˆλ‹€.
14+
3. ν˜„μž¬ 주식 κ°€κ²©μ—μ„œ `min_price`λ₯Ό λΊ€ κ°’(ν˜„μž¬ 이읡)이 `max_profit`보닀 크면, `max_profit`을 κ°±μ‹ ν•©λ‹ˆλ‹€.
15+
- `max_profit`은 ν˜„μž¬κΉŒμ§€μ˜ μ΅œλŒ€ 이읡을 μ˜λ―Έν•©λ‹ˆλ‹€.
16+
4. λ°°μ—΄ μˆœνšŒκ°€ λλ‚œ ν›„, `max_profit`을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
17+
18+
μ‹œκ°„ λ³΅μž‘λ„:
19+
- 배열을 ν•œ 번만 μˆœνšŒν•˜λ―€λ‘œ O(n)μž…λ‹ˆλ‹€.
20+
21+
곡간 λ³΅μž‘λ„:
22+
- 좔가적인 λ°°μ—΄μ΄λ‚˜ 데이터 ꡬ쑰λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³ , 두 개의 λ³€μˆ˜(`min_price`, `max_profit`)만 μ‚¬μš©ν•˜λ―€λ‘œ O(1)μž…λ‹ˆλ‹€.
23+
*/
24+
25+
function maxProfit(prices) {
26+
let min_price = Infinity; // 초기 μ΅œμ†Œκ°’μ„ λ¬΄ν•œλŒ€λ‘œ μ„€μ • (μ–΄λ–€ κ°’κ³Ό 비ꡐ해도 κ°±μ‹ λ˜λ„λ‘ μ„€μ •)
27+
let max_profit = 0; // 초기 μ΅œλŒ€ 이읡은 0 (이읡이 없을 κ²½μš°μ—λ„ 0을 λ°˜ν™˜ν•΄μ•Ό 함)
28+
29+
// 배열을 μˆœνšŒν•˜λ©° μ΅œμ†Œ 맀수 가격과 μ΅œλŒ€ 이읡을 계산
30+
for (let price of prices) {
31+
if (price < min_price) {
32+
// ν˜„μž¬ 주식 가격이 μ΅œμ†Œ 맀수 가격보닀 μž‘μœΌλ©΄ μ΅œμ†Œ 맀수 가격 κ°±μ‹ 
33+
min_price = price;
34+
} else if (price - min_price > max_profit) {
35+
// ν˜„μž¬ 주식 κ°€κ²©μ—μ„œ μ΅œμ†Œ 맀수 가격을 λΊ€ κ°’(ν˜„μž¬ 이읡)이 μ΅œλŒ€ 이읡보닀 크면 μ΅œλŒ€ 이읡 κ°±μ‹ 
36+
max_profit = price - min_price;
37+
}
38+
}
39+
40+
return max_profit; // μ΅œλŒ€ 이읡 λ°˜ν™˜
41+
}

0 commit comments

Comments
Β (0)