-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxProfit.js
50 lines (43 loc) · 1.22 KB
/
maxProfit.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
45
46
47
48
49
50
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
// use two pointers
// if don't have stock and slow is greater than fast, buy slow
// sell when you reach a point where it is no longer increasing there will be the greatest profit
let slow = 0;
let fast = 1;
let total = 0;
let haveStock = false;
while (slow !== fast && fast < prices.length) {
// console.log('initial total ', total)
// console.log('slow', slow, 'fast', fast)
if (prices[slow] < prices[fast] && !haveStock) {
// buy slow
total = total - prices[slow];
haveStock = true;
// console.log('buying', 'new total is ', total)
} else if (
prices[slow] > prices[fast] &&
total + prices[slow] > 0 &&
haveStock
) {
//sell now
haveStock = false;
total = total + prices[slow];
// console.log('selling', 'new total is ', total)
}
fast++;
slow++;
}
if (haveStock) {
total = Math.max(total, total + prices[prices.length - 1]);
}
return Math.max(total, 0);
};
console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 7
console.log(maxProfit([1, 2, 3, 4, 5])); // 4
// total = 0
// 1,2 - hasStock, total = -1
// 2,3 - !hasStock, total =