forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0121-best-time-to-buy-and-sell-stock.js
44 lines (38 loc) · 1.05 KB
/
0121-best-time-to-buy-and-sell-stock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
* Time O(N) | Space O(1)
* @param {number} prices
* @return {number}
*/
var maxProfit = function (prices) {
let [left, right, max] = [0, 1, 0];
while (right < prices.length) {
const canSlide = prices[right] <= prices[left];
if (canSlide) left = right;
const window = prices[right] - prices[left];
max = Math.max(max, window);
right++;
}
return max;
};
/**
* Another approach without using sliding window
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
* Time O(N) | Space O(1)
* @param {number} prices
* @return {number}
*/
var maxProfit = function (prices) {
let min = prices[0];
let max = min;
let value = 0;
for (let i = 0; i < prices.length; i++) {
if (i != prices.length - 1 && prices[i] <= min) {
max = min = prices[i];
} else if (prices[i] > max) {
max = prices[i];
}
value = max - min > value ? max - min : value;
}
return value;
};