Skip to content

Commit cc061c9

Browse files
committed
feat: 121. Best Time to Buy and Sell Stock
1 parent 390e210 commit cc061c9

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+
// Time complexity: O(n)
2+
// Space complexity: O(1)
3+
4+
/**
5+
* @param {number[]} prices
6+
* @return {number}
7+
*/
8+
var maxProfit = function (prices) {
9+
let answer = 0;
10+
let minValue = Number.MAX_SAFE_INTEGER;
11+
12+
for (const price of prices) {
13+
minValue = Math.min(minValue, price);
14+
answer = Math.max(answer, price - minValue);
15+
}
16+
17+
return answer;
18+
};

0 commit comments

Comments
 (0)