Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions best-time-to-buy-and-sell-stock/reeseo3o.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Step 1. 브루트 포스
// 시간 복잡도: O(n²)
const maxProfitBrute = (prices) => {
let maxProfit = 0;

for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
const profit = prices[j] - prices[i];
maxProfit = Math.max(maxProfit, profit);
}
}

return maxProfit;
}

// Step 2. 최적 풀이
// 시간 복잡도: O(n)
const maxProfit = (prices) => {
let minPrice = Infinity;
let maxProfit = 0;

for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}

return maxProfit;
}
Comment on lines +16 to +31
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

깔끔하네요. 보니까 저는 불필요하게 투 포인터로 접근했네요.

Loading