Skip to content

Commit 9075685

Browse files
committed
week5: best-time-to-buy-and-sell-stock
1 parent 8a4a45d commit 9075685

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Step 1. 브루트 포스
2+
// 시간 복잡도: O(n²)
3+
const maxProfitBrute = (prices) => {
4+
let maxProfit = 0;
5+
6+
for (let i = 0; i < prices.length; i++) {
7+
for (let j = i + 1; j < prices.length; j++) {
8+
const profit = prices[j] - prices[i];
9+
maxProfit = Math.max(maxProfit, profit);
10+
}
11+
}
12+
13+
return maxProfit;
14+
}
15+
16+
// Step 2. 최적 풀이
17+
// 시간 복잡도: O(n)
18+
const maxProfit = (prices) => {
19+
let minPrice = Infinity;
20+
let maxProfit = 0;
21+
22+
for (const price of prices) {
23+
if (price < minPrice) {
24+
minPrice = price;
25+
} else {
26+
maxProfit = Math.max(maxProfit, price - minPrice);
27+
}
28+
}
29+
30+
return maxProfit;
31+
}

0 commit comments

Comments
 (0)