Dynamic Programming (Hackerrank WalmartLabs-codesprint)

Can someone please explain the dynamic programing solution to this problem.

This problem can be solved by knowledge of ‘Catalan Number’. You can read on this: http://www.geeksforgeeks.org/applications-of-catalan-numbers/ and https://en.wikipedia.org/wiki/Catalan_number .
Here is dynamic solution to find n’th catalan number:

long long int catalan[4002];
void precalc()
{
      catalan[0] = 1;
      for(int i=1;i<=4001;i++)
      {
          if(i==1)
                catalan* = 1;
          else
          {
                long long int sum =0,left,right;
                for(int k=0;k<i;k++)
                {
                      left = catalan[k]%MOD;
                      right = catalan[(i-1)-k]%MOD;
                      sum = (sum + (left*right)%MOD)%MOD;
                }
                catalan* = sum;
          }
      }
}

You could also check out this article on catalan numbers.As catalan numbers are defined recursively it can be easily converted into itarative dp(similar to fibonacci).Just undestand how we arrive at the series coding this into dp is quite intutive. for solution you may refer to geeksforgeeks.

1 Like

This was the function I used in Java:

static long[] catalanDP(int n)
    {
        long[] f = new long[n+1];
        f[0] = f[1] = 1;
        for(int i=2;i<=n;i++)
        {
            for(int j=0;j<i;j++)
                f* = (f* + (f[j] % MOD * f[i-1-j] % MOD)) % MOD;
        }

        return f;
    }