54.3k views
1 vote
how would you find the length of the longest common subsequence of elements in two arrays dynamic programming

1 Answer

5 votes

Final answer:

To find the length of the longest common subsequence of elements in two arrays using dynamic programming, create a table, compare elements, and take the maximum value to find the length.

Step-by-step explanation:

To find the length of the longest common subsequence of elements in two arrays using dynamic programming, you can follow the following steps:

  1. Create a table to store the lengths of the common subsequences.
  2. Initialize the first row and column of the table with zeros.
  3. Iterate through each element of the two arrays.
  4. If the elements are the same, add 1 to the value in the cell diagonally above-left in the table.
  5. If the elements are different, take the maximum value between the cell above or the cell to the left in the table and store it in the current cell.
  6. The value in the bottom-right cell of the table would represent the length of the longest common subsequence.

For example, consider two arrays [1, 2, 4, 5] and [1, 3, 4, 5]. The table would look like this:
|| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 | 0 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 |
| 3 | 0 | 1 | 1 | 1 |
| 4 | 0 | 1 | 2 | 2 |
| 5 | 0 | 1 | 2 | 2 |

User Leon Young
by
7.5k points