Consider a table , where the elements , represent the cost of the optimal solutions of different subproblems of a problem that is being solved using a dynamic programming algorithm. The recursive formulation to compute the table entries is as follows:
Consider the following two algorithms to compute entries of . Assume that for both the algorithms, for all has been initialized to .
Algorithm : For
Algorithm For
Algorithm is said to be correct if and only if it calculates the correct values of , for all , (as per the recursive formulation) at the end of the execution of the algorithm .
Which one of the following statements is true?
View worked solution
Answer: A
To determine the correctness of the algorithms, we need to analyze the dependency of the recurrence relation:
To compute the value at cell , we must have already computed the values at:
- Top neighbor:
- Left neighbor:
1. Analysis of Algorithm
Algorithm uses a standard row-by-row traversal:
- The outer loop runs from to .
- The inner loop runs from to .
When computing :
- belongs to the previous row , which has already been completely computed.
- belongs to the same row but the previous column , which has already been computed in the previous iteration of the inner loop.
Since both dependencies are satisfied, Algorithm is correct.
2. Analysis of Algorithm
Algorithm groups the computations by the sum of indices :
- The outer loop runs from to .
- The inner loops iterate over all pairs such that .
When computing for a given sum :
- The required element has index sum .
- The required element has index sum .
Since the outer loop processes the sums in strictly increasing order (), all cells with index sum are guaranteed to be computed before we process any cell with index sum .
Thus, both dependencies are always satisfied, and Algorithm is correct.
Therefore, both algorithms and are correct.
Free practice · Your answers on this page are not saved.
