Skip to content

Commit facd989

Browse files
authored
Merge pull request neetcode-gh#1541 from elcabalero/patch-10
Updated code as in the video adapting to C++
2 parents 29aa700 + 5ef587d commit facd989

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

cpp/neetcode_150/14_2-d_dynamic_programming/best_time_to_buy_and_sell_stock_with_cooldown.cpp

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
sell rest buy
88
99
Time: O(n)
10-
Space: O(1) -> optimized from O(n) since only need i - 1 prev state
10+
Space: O(n)
1111
*/
1212

1313
// class Solution {
@@ -28,7 +28,9 @@
2828
// return max(s0[n - 1], s2[n - 1]);
2929
// }
3030
// };
31-
31+
//
32+
// Optimized solution with O(1) space follows
33+
/*
3234
class Solution {
3335
public:
3436
int maxProfit(vector<int>& prices) {
@@ -46,3 +48,37 @@ class Solution {
4648
return max(sold, rest);
4749
}
4850
};
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

Comments
 (0)