Need Optimizations for this code


#1

int rec(vector &A, int n,int B,int mx,vector<vector>&t){
if(n==0||B==0) return 0;
if(t[n][B]!=-1) return t[n][B];
if(A[n-1]>mx){
mx=A[n-1];
return t[n][B]=rec(A,n-1,B,mx,t);
}
else{
if(A[n-1]<mx){
return t[n][B]=max((mx-A[n-1])+rec(A,n-1,B-1,A[n-1],t),rec(A,n-1,B,mx,t));

    }
    else return t[n][B]=rec(A,n-1,B,mx,t);
}

}
int Solution::solve(vector &A, int B) {
int n=A.size();

if(B>n) B=n;
int mx=*max_element(A.begin(),A.end());
vector<vector<int>>t(n+1,vector<int>(B+1,-1));
return rec(A,n,B,0,t);

}