title: DP based algo for Stock maximize problem Hackerank
body: <p>I need some help solving the Stock maximize problem on hackerrank the problem is at this link <a href="https://www.hackerrank.com/challenges/stockmax/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/stockmax/problem</a>
  I know there's a linear approach to solve this problem but I needed help with Dynamic Programming involving a 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 the answer</p>
  <pre><code>long myans(vector&lt;int&gt; prices, unordered_map&lt;int,unordered_map&lt;int, long&gt;&gt; &amp;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&gt;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&lt;int&gt; prices) {
  unordered_map&lt;int,unordered_map&lt;int, long&gt;&gt; mp;
     return myans(prices,mp,0,0,0);
  
  }
  </code></pre>