Skip to content

Commit 179480a

Browse files
committed
best-time-to-buy-and-sell-stock solution
1 parent e9bff47 commit 179480a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
// 초기 값
7+
let buy = prices[0];
8+
// 차액
9+
let diff = 0;
10+
11+
for (let i = 1; i < prices.length; i++) {
12+
// 구매가보다 현재가격이 더 싸면 구매가로 변경
13+
if (buy > prices[i]) {
14+
buy = prices[i];
15+
}
16+
// 차액 계산, 누가더 큰지 비교
17+
diff = Math.max(diff, (prices[i] - buy));
18+
19+
}
20+
return diff
21+
};

0 commit comments

Comments
 (0)