-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
32 lines (25 loc) · 729 Bytes
/
Copy pathsolution.js
File metadata and controls
32 lines (25 loc) · 729 Bytes
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
/**
* @param {number[]} arr
* @param {number} k
* @returns {number}
*/
class Solution {
maxProfit(arr, k) {
let n = arr.length;
// hold = maximum profit when I currently have a stock
let hold = -arr[0];
// cash = maximum profit when I do not have a stock
let cash = 0;
for (let i = 1; i < n; i++) {
// Save previous cash because hold depends on old cash
let prevCash = cash;
// Either keep holding previous stock
// Or buy stock today
hold = Math.max(hold, prevCash - arr[i]);
// Either keep previous cash
// Or sell stock today and pay fee
cash = Math.max(cash, hold + arr[i] - k);
}
return cash;
}
}