Recursive Approach Leads To TLE: Optimize With DP
Recursive approach leads to TLE, use DP or simple iterative solution instead.
Buy and sell stocks
this will lead to TLE:
TC: exponential as we will be recursively calling the mProfit method, sc: recursive stack space
class Solution {
public int maxProfit(int[] prices) {
return mProfit(0,0,prices);
}
public int mProfit(int index ,int canBuy, int[] prices){
//base case
if(index==prices.length || canBuy==2) return 0;
int max = Integer.MIN_VALUE;
int buy = 0;
int sell = 0;
if(canBuy==0){
buy = Integer.max(
-prices[index] + mProfit(index+1,1,prices),
mProfit(in...