lundi 28 décembre 2020

DP based algo for Stock maximize problem Hackerank

i need some help solving Stock maximize problem on hackerrank the problem is at this link https://www.hackerrank.com/challenges/stockmax/problem I know there's a linear approach to solve this problem but i needed help with Dynamic Programming involving solution of mine.. It gives TLE when i submit it.. As a learner i just want to know is there any further optimization i can do to my DP based solution. I wrote the following function to evaluate answer

long myans(vector<int> prices, unordered_map<int,unordered_map<int, long>> &mp ,int st,long ns,long pr)
{
   //base
   if(st==prices.size())
   return pr;
   //dp
   if( mp[ns][st]!=0)
   return  mp[ns][st];
   //rec
   long dn=0,ss=0,bs=0;
   if(st!=prices.size()-1)
   bs=myans(prices,mp,st+1,ns+1,pr-prices[st]);
   if(ns>0)
   ss=myans(prices,mp,st+1,0,pr+ns*prices[st]);
   dn=myans(prices,mp,st+1,ns,pr);
   mp[ns][st]=max(bs,max(ss,dn));
   // mp[st+1][ns+1]=bs;
   // mp[st+1][ns]=dn;
   // mp[st+1][0]=ss;
    return mp[ns][st];
   //return  mp[make_pair(ns,prices[st])];
}
long stockmax(vector<int> prices) {
unordered_map<int,unordered_map<int, long>> mp;
   return myans(prices,mp,0,0,0);

}

Aucun commentaire:

Enregistrer un commentaire