📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    In the dynamic programming solution for Matrix Chain

    Multiplication, the outermost loop iterates over the len (chain length). What are the correct loop bounds for len and i? // n is the number of matrices (arr.size() for dimensions array) // dp is a 2D array for (int len = __________) { // Line to complete len loop     for (int i = __________); i < n - len; i++) { // Line to complete i loop         int j = i + len;         // ... inner k loop and calculations     } }
    A len = 1; len < n; len++ and i = 0 Correct Answer Incorrect Answer
    B len = 2; len < n; len++ and i = 0 Correct Answer Incorrect Answer
    C len = 2; len <= n; len++ and i = 1 Correct Answer Incorrect Answer
    D len = 1; len <= n; len++ and i = 1 Correct Answer Incorrect Answer
    E len = 0; len < n; len++ and i = 0 Correct Answer Incorrect Answer

    Solution

    • Code Analysis: o n is the number of matrices. o len should iterate from the smallest possible chain length (2 matrices) up to the total number of matrices (n). o i should iterate through all possible starting points for a subproblem of length len. o j = i + len calculates the ending index of the subproblem. • Explanation of Correct Answer (B): len = 2; len < n; len++ and i = 0 o len loop:  len starts from 2 because a chain of length 1 (a single matrix) requires no multiplication. The smallest meaningful chain is two matrices.  len < n: The chain length len goes up to n-1 (if n is the number of matrices, then n-1 is the maximum chain length for subproblems, as j goes up to n-1). If n is the size of the arr (dimensions array), then n-1 is the number of matrices. The loop should go up to n-1 matrices, so len < n is correct. o i loop:  i starts from 0 because the first matrix can be at index 0.  i < n - len: This ensures that j = i + len does not exceed the bounds of the matrix array. If n is the number of matrices, then i can go up to n - len. For example, if len = n-1, i can only be 0.

    Practice Next
    ask-question