LCS of 3 strings - Coding Ninjas Codestudio

PHOTO EMBED

Tue Sep 06 2022 17:13:57 GMT+0000 (Coordinated Universal Time)

Saved by @bracketcoder #3d-array #dp

int LCS(string a, string b, string c, int n, int m, int k)
{
   vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(m + 1, vector<int>(k + 1, 0)));
   
   for(int s1 = 1;s1 <= n; s1++)
   {
       for(int s2 = 1;s2 <= m; s2++)
       {
           for(int s3 = 1;s3 <= k;s3++)
           {
               int inc = -1e9;
               if(a[s1 - 1] == b[s2 - 1] and a[s1 - 1] == c[s3 - 1])
               {
                   inc = 1 + dp[s1 - 1][s2 - 1][s3 - 1];
               }

               int *arr = new int[6];

               arr[0] = dp[s1 - 1][s2][s3];
               arr[1] = dp[s1][s2 - 1][s3];
               arr[2] = dp[s1][s2][s3 - 1];
               arr[3] = dp[s1 - 1][s2 - 1][s3];
               arr[4] = dp[s1 - 1][s2][s3 - 1];
               arr[5] = dp[s1][s2 - 1][s3 - 1];

               int maxi = -1e9;

               for(int i=0;i<6;i++)
               {
                   maxi = max(maxi, arr[i]);
               }

               dp[s1][s2][s3] = max(maxi, inc);
               delete arr;
           }
       }
   }
   
   return dp[n][m][k];
   
}
content_copyCOPY

https://www.codingninjas.com/codestudio/guided-paths/data-structures-algorithms