Skip to content

Commit 1d88643

Browse files
committed
Best Time To Buy And Sell Stock Solution
1 parent 022dd7d commit 1d88643

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
6+
/**
7+
* Runtime: 73ms, Memory: 59.38MB
8+
* n = prices.length
9+
* Time complexity: O(n)
10+
* Space complexity: O(1)
11+
*
12+
*/
13+
14+
var maxProfit = function (prices) {
15+
let minPrice = prices[0];
16+
let maxPrice = prices[0];
17+
let answer = 0;
18+
19+
for (let i = 1; i < prices.length; i++) {
20+
answer = Math.max(answer, maxPrice - minPrice);
21+
22+
// 가장 뒤쪽 값이 max일 때
23+
if (maxPrice < prices[i]) {
24+
maxPrice = prices[i];
25+
answer = Math.max(answer, maxPrice - minPrice);
26+
continue;
27+
}
28+
// 가장 뒷쪽 값이 min일 때
29+
if (minPrice > prices[i]) {
30+
minPrice = prices[i];
31+
maxPrice = prices[i];
32+
}
33+
}
34+
return answer;
35+
};

0 commit comments

Comments
 (0)