Skip to content

Commit e7e9cef

Browse files
committed
best-time-to-buy-and-sell-stock
1 parent 126607d commit e7e9cef

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* 시간 복잡도: O(n) - 배열을 한 번만 순회함
3+
* 공간 복잡도: O(1) - 추가 배열 없이 변수만 사용하므로 입력 크기와 무관한 상수 공간
4+
*/
5+
/**
6+
* @param {number[]} prices
7+
* @return {number}
8+
*/
9+
var maxProfit = function (prices) {
10+
let minPrice = prices[0]; // 지금까지 본 가장 낮은 가격
11+
let maxProfit = 0; // 최대 이익
12+
for (let i = 1; i < prices.length; i++) {
13+
if (prices[i] > minPrice) {
14+
// 현재 가격이 minPrice보다 큰 경우에 이익 갱신
15+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
16+
} else {
17+
// 그렇지 않다면 최소 가격 갱신
18+
minPrice = prices[i];
19+
}
20+
}
21+
return maxProfit;
22+
};

0 commit comments

Comments
 (0)