Skip to content

Commit 211ac1b

Browse files
committed
solve: best time to buy and sell stock
1 parent 94bfcdb commit 211ac1b

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+
* TC: O(N)
3+
* SC: O(1)
4+
*/
5+
6+
/**
7+
* @param {number[]} prices
8+
* @return {number}
9+
*/
10+
var maxProfit = function (prices) {
11+
let maximumProfit = 0;
12+
let minimumPrice = prices[0];
13+
14+
for (const price of prices) {
15+
// 매일 (그날까지의) 최소 구매가를 기록합니다.
16+
minimumPrice = Math.min(minimumPrice, price);
17+
// 최대 이익을 갱신합니다.
18+
maximumProfit = Math.max(maximumProfit, price - minimumPrice);
19+
}
20+
21+
return maximumProfit;
22+
};

0 commit comments

Comments
 (0)