Skip to content

Commit 3ec3042

Browse files
committed
besta time to buy and sell stock solution
1 parent d52bb73 commit 3ec3042

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function(prices) {
6+
7+
// 최대 수익
8+
let maxProfit = 0;
9+
// prices 배열의 0번째를 최소 가격으로 시작
10+
let minPrice = prices[0];
11+
12+
// prices 배열 for문 돌려서 최대 수익 찾기
13+
for(let i=0; i<prices.length; i++) {
14+
minPrice = Math.min(minPrice, prices[i]);
15+
let current = prices[i] - minPrice;
16+
maxProfit = Math.max(current, maxProfit);
17+
}
18+
// 최대 수익 반환
19+
return maxProfit;
20+
21+
};
22+
23+
// 시간 복잡도: O(n)
24+
// 공간 복잡도: O(1)

0 commit comments

Comments
 (0)