Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Dynamic Programming Solutions in Java: Matrix Chain Multiplication and Longest Common Subsequence

Tech May 13 1

Matrix Chain Mulitplication

Matrix chain multiplication finds the optimal parenthesization to minimize scalar multiplications. The recurrence relation is:

m[i,j] = 0 if i = j
        min(m[i,k] + m[k+1,j] + p[i-1]*p[k]*p[j]) for i ≤ k < j if i < j

Three nested loops are required:

  • Outer loop: chain length
  • Middle loop: starting index
  • Inner loop: partition point within the current chain
public class MatrixChainOptimization {
    public static int computeOptimalCost(int[] dimensions) {
        int n = dimensions.length - 1;
        int[][] costTable = new int[n][n];
        
        for (int chainLen = 2; chainLen <= n; chainLen++) {
            for (int start = 0; start <= n - chainLen; start++) {
                int end = start + chainLen - 1;
                costTable[start][end] = Integer.MAX_VALUE;
                
                for (int split = start; split < end; split++) {
                    int currentCost = costTable[start][split] + 
                                    costTable[split + 1][end] + 
                                    dimensions[start] * dimensions[split + 1] * dimensions[end + 1];
                    
                    if (currentCost < costTable[start][end]) {
                        costTable[start][end] = currentCost;
                    }
                }
            }
        }
        return costTable[0][n - 1];
    }
}

Longest Common Subsequence

The longest common subsequence (LCS) problem finds the longest sequence present in both strings. The recurrence is:

lcs[i,j] = 0 if i = 0 or j = 0
          lcs[i-1,j-1] + 1 if chars match
          max(lcs[i-1,j], lcs[i,j-1]) otherwise
public class LongestCommonSubsequence {
    public static int findLCSLength(String str1, String str2) {
        char[] seq1 = str1.toCharArray();
        char[] seq2 = str2.toCharArray();
        int[][] lcsTable = new int[seq1.length + 1][seq2.length + 1];
        
        for (int i = 1; i <= seq1.length; i++) {
            for (int j = 1; j <= seq2.length; j++) {
                if (seq1[i - 1] == seq2[j - 1]) {
                    lcsTable[i][j] = lcsTable[i - 1][j - 1] + 1;
                } else {
                    lcsTable[i][j] = Math.max(lcsTable[i - 1][j], lcsTable[i][j - 1]);
                }
            }
        }
        return lcsTable[seq1.length][seq2.length];
    }
}

Dynamic programming problems require identifying optimal substrutcure and overlapping subproblems. Key variables typically represent problem dimensions or states, and solutions build up from smaller subproblems to the complete solution.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.