7
7
sell rest buy
8
8
9
9
Time: O(n)
10
- Space: O(1) -> optimized from O(n) since only need i - 1 prev state
10
+ Space: O(n)
11
11
*/
12
12
13
13
// class Solution {
28
28
// return max(s0[n - 1], s2[n - 1]);
29
29
// }
30
30
// };
31
-
31
+ //
32
+ // Optimized solution with O(1) space follows
33
+ /*
32
34
class Solution {
33
35
public:
34
36
int maxProfit(vector<int>& prices) {
@@ -46,3 +48,37 @@ class Solution {
46
48
return max(sold, rest);
47
49
}
48
50
};
51
+ */
52
+
53
+ // NeetCode's solution
54
+ // Uses an array of arrays of size two (i.e. a n x 2 matrix)
55
+ // representing at position 0 of each row the "selling" value
56
+ // whereas at position 1 the "buying" value.
57
+ // Could've used a map<pair<int,int>> instead of the bidimensional
58
+ // array at the expense of logn search.
59
+ class Solution {
60
+ public:
61
+ int maxProfit (vector<int >& prices) {
62
+ vector<vector<int >> DP (prices.size (), vector<int >(2 , -1 ));
63
+ return dfs (prices, DP, 0 , 1 );
64
+ }
65
+
66
+ private:
67
+ int dfs (vector<int >& prices, vector<vector<int >>& DP, int i, int buying){
68
+ if (i >= prices.size ())
69
+ return 0 ;
70
+ if (DP[i][buying] != -1 )
71
+ return DP[i][buying];
72
+
73
+ int cooldown = dfs (prices, DP, i+1 , buying);
74
+ if (buying){
75
+ int buy = dfs (prices, DP, i+1 , 0 ) - prices[i];
76
+ DP[i][buying] = max (buy, cooldown);
77
+ } else {
78
+ int sell = dfs (prices, DP, i+2 , 1 ) + prices[i];
79
+ DP[i][buying] = max (sell, cooldown);
80
+ }
81
+
82
+ return DP[i][buying];
83
+ }
84
+ };
0 commit comments