Skip to content

Commit af47da3

Browse files
committed
Best Time to Buy And Sell Stock
1 parent 8246eb1 commit af47da3

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
let minPrice = Infinity;
7+
let maxProfit = 0;
8+
9+
for (let i = 0; i < prices.length; i++) {
10+
if (prices[i] < minPrice) {
11+
minPrice = prices[i];
12+
} else {
13+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
14+
}
15+
}
16+
17+
return maxProfit;
18+
19+
};
20+
21+
console.log(maxProfit([7, 1, 5, 3, 6, 4]));
22+
console.log(maxProfit([7, 6, 4, 3, 1]));
23+
24+
/*
25+
시간 복잡도: O(n)
26+
공간 복잡도: O(1)
27+
*/

0 commit comments

Comments
 (0)