📜  门| GATE-CS-2006 |问题 10(1)

📅  最后修改于: 2023-12-03 15:12:41.621000             🧑  作者: Mango

GATE-CS-2006 Problem 10

This is a programming question from the GATE-CS-2006 exam. The problem aims to test a candidate's understanding of dynamic programming.

Problem Statement

Given an array of numbers, find the length of the longest increasing subsequence (LIS).

For example, suppose we have an array [10, 22, 9, 33, 21, 50, 41, 60, 80]. The LIS is [10, 22, 33, 50, 60, 80], and its length is 6.

Solution

This problem can be solved using dynamic programming by maintaining an array lis of the same length as the input array arr.

In the lis array, lis[i] stores the length of the LIS ending at index i in the arr array.

The LIS length for index i can be determined as follows:

  1. Initialize lis[i] to 1.
  2. For all indices j less than i, if arr[j] < arr[i], then lis[i] = max(lis[i], lis[j] + 1).

Finally, the maximum value in the lis array gives the length of the longest increasing subsequence.

Here is the Python code for this algorithm:

def lis_length(arr):
    n = len(arr)
    lis = [1] * n

    for i in range(1, n):
        for j in range(i):
            if arr[j] < arr[i]:
                lis[i] = max(lis[i], lis[j] + 1)

    return max(lis)
Conclusion

This problem required the use of dynamic programming to solve. Maintaining an array of the longest increasing subsequences ending at each index is the key to this algorithm.

The time complexity of this algorithm is O(n^2), where n is the length of the input array.