WalzoneInterview Prep
๐Ÿ“ž Interviewing soon? Practice with a realistic AI mock phone interview โ€” it calls you, then scores you. First 15 min FREE โ†’

Dynamic Programming ยท Intermediate ยท question 32 of 100

How can you use dynamic programming to solve the Maximum Length Chain of Pairs problem? Implement the solution.?

๐Ÿ“• Buy this interview preparation book: 100 Dynamic Programming questions & answers โ€” PDF + EPUB for $5

The Maximum Length Chain of Pairs problem can be solved using dynamic programming.

The problem is as follows: given an array of pairs (a1, b1), (a2, b2), ..., (an, bn), each pair (ai, bi) represents a directed edge from vertex ai to vertex bi, find the maximum length chain of pairs that can be formed. A chain of pairs is a sequence of pairs (ai, bi), (aj, bj), ..., (ak, bk) where (aj, bj) is directed from vertex ai to vertex aj.

The solution using dynamic programming involves sorting the array of pairs based on the second element (the b value) in increasing order. We then define an array dp where dp[i] represents the length of the longest chain that ends at pair i. We can then compute dp[i] by iterating over all pairs j where b[j] < a[i], and updating the value of dp[i] to max(dp[i], dp[j] + 1). The final answer is the maximum value in the dp array.

Here is the Java code for the solution:

public int findMaxChainLength(Pair[] pairs) {
    Arrays.sort(pairs, Comparator.comparingInt(pair -> pair.b));
    int[] dp = new int[pairs.length];
    Arrays.fill(dp, 1);
    for (int i = 1; i < pairs.length; i++) {
        for (int j = 0; j < i; j++) {
            if (pairs[j].b < pairs[i].a) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
    }
    int maxLength = 0;
    for (int len : dp) {
        maxLength = Math.max(maxLength, len);
    }
    return maxLength;
}

In this code, we first sort the array of pairs based on the second element (b value). We then initialize the dp array with 1, since the length of a chain that consists of only one pair is always 1. We then iterate over all pairs i (starting from the second one) and all pairs j (before i), and update the value of dp[i] if b[j] < a[i]. Finally, we loop over the dp array and find the maximum value, which represents the length of the maximum length chain of pairs.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview โ€” then scores it.
๐Ÿ“ž Practice Dynamic Programming โ€” free 15 min
๐Ÿ“• Buy this interview preparation book: 100 Dynamic Programming questions & answers โ€” PDF + EPUB for $5

All 100 Dynamic Programming questions ยท All topics