📜  门| GATE-CS-2017(Set 2)|第64章(1)

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

GATE-CS-2017(Set 2) Question 64

This question is a coding assignment that requires the implementation of an algorithm to find the longest increasing subsequence of a given sequence of integers.

Problem Statement

Given a sequence of n integers, find the longest increasing subsequence (LIS).

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For example, the subsequence of [1, 2, 3, 4] that consists of [1, 3, 4] is a valid subsequence.

An increasing subsequence is a subsequence in which the elements are in increasing order. For example, [1, 3, 4] is an increasing subsequence of [1, 2, 3, 4].

The LIS problem can be solved using dynamic programming. The basic idea is to maintain a table where each entry is the length of the longest increasing subsequence that ends at that position in the input sequence.

Algorithm
def longest_increasing_subsequence(sequence):
    n = len(sequence)
    dp = [1] * n
    for i in range(1, n):
        for j in range(i):
            if sequence[j] < sequence[i]:
                dp[i] = max(dp[i], dp[j] + 1)
    return max(dp)

In this algorithm, dp is the table that we maintain. dp[i] is the length of the longest increasing subsequence that ends at position i in the input sequence. We initialize all entries in dp to 1, since every element is a valid subsequence of length 1.

We then iterate over the input sequence, and for each position i, we iterate over all positions before i (denoted by j). If the value at j is less than the value at i, then we can extend the LIS that ends at j to include i. We update the length of the LIS that ends at i by taking the maximum of its current value and the length of the LIS that ends at j plus 1.

Finally, we return the maximum value in dp, which is the length of the longest increasing subsequence in the input sequence.

Time Complexity

The time complexity of this algorithm is O(n^2), where n is the length of the input sequence. This is because we perform a nested loop over the input sequence to fill in the dp table. However, it is possible to improve the time complexity to O(n log n) using a binary search algorithm.