05. Stock buy and sell II
My Approach
Recurrence recursive code (c++) (Gives TLE)
class Solution {
public:
int check(int i, int n, vector<int>& prices, int sum, int canBuy) {
if (i == n) // Base case
return sum;
int out = check(i + 1, n, prices, sum, canBuy);
if (canBuy) {
out = max(out, check(i + 1, n, prices, sum - prices[i], 0)); // For Buying
} else {
out = max(out, check(i + 1, n, prices, sum + prices[i], 1)); // For Selling
}
return out;
}
int stockBuyAndSell(int n, vector<int>& prices) {
return check(0, n, prices, 0, 1);
}
};
Optimized approach
Time and Auxiliary Space Complexity
Code (C++) (Tabulation)
Contribution and Support
Last updated