Skip to content

Commit f5afe89

Browse files
committed
feat: best time to buy and sell stock
1 parent 7ae7503 commit f5afe89

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* 시간 복잡도: prices.length만큼 순회하므로 O(n)
3+
* 공간 복잡도: 상수 크기의 변수만 사용하므로 O(1)
4+
*/
5+
/**
6+
* @param {number[]} prices
7+
* @return {number}
8+
*/
9+
var maxProfit = function (prices) {
10+
let maxProfit = 0;
11+
let min = prices[0];
12+
13+
for (let i = 0; i < prices.length; i++) {
14+
maxProfit = Math.max(maxProfit, prices[i] - min);
15+
min = Math.min(min, prices[i]);
16+
}
17+
return maxProfit;
18+
};

0 commit comments

Comments
 (0)