Skip to content

Commit 2ed89c4

Browse files
committed
best time to buy and sell stock solution
1 parent 807a383 commit 2ed89c4

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 핡심 아이디어:
3+
* μ–΄λ–€ 날에 주식을 νŒ” λ•Œ μ΅œλŒ€ 이읡을 μ–»μœΌλ €λ©΄,
4+
* κ·Έ λ‚  μ΄μ „μ˜ μ΅œμ €κ°€μ— 샀어야 ν•œλ‹€.
5+
* λ”°λΌμ„œ 배열을 μˆœνšŒν•˜λ©΄μ„œ "μ§€κΈˆκΉŒμ§€μ˜ μ΅œμ €κ°€"만 μΆ”μ ν•˜κ³ ,
6+
* λ§€ μ‹œμ λ§ˆλ‹€ (ν˜„μž¬κ°€ - μ΅œμ €κ°€)둜 잠재 이읡을 κ³„μ‚°ν•˜λ©΄ λœλ‹€.
7+
*
8+
* μ‹œκ°„ λ³΅μž‘λ„: O(n) - 배열을 ν•œ 번만 순회
9+
* 곡간 λ³΅μž‘λ„: O(1) - λ³€μˆ˜ 2개만 μ‚¬μš©
10+
*/
11+
const maxProfit = (prices) => {
12+
let minPrice = prices[0];
13+
let maxProfit = 0;
14+
15+
for (let i = 1; i < prices.length; i++) {
16+
const price = prices[i];
17+
if (price < minPrice) {
18+
minPrice = price;
19+
} else if (price - minPrice > maxProfit) {
20+
maxProfit = price - minPrice;
21+
}
22+
}
23+
24+
return maxProfit;
25+
};

0 commit comments

Comments
Β (0)