📜  门| GATE-CS-2017(Set 2)|问题30(1)

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

GATE-CS-2017(Set 2) Problem 30

Introduction

This question is a part of GATE-CS-2017 (Set 2) and is related to dynamic programming. The problem requires the programmer to find the longest increasing subsequence of an array with a twist that if two elements are equal, they cannot be part of the same subsequence.

Problem Explanation

Given an array A with n integers, find the length of the longest increasing subsequence of A such that no two elements in the subsequence are equal.

Approach

We can solve this problem using dynamic programming. For each index i in the array, we can find the length of the longest increasing subsequence ending at i such that no two elements are equal. We can store this value in an array dp[i].

To find dp[i], we can iterate over all indices j less than i and check if A[i] > A[j] and A[i] != A[j]. If both of these conditions are satisfied, then we can update dp[i] to max(dp[i], dp[j]+1).

The final answer will be the maximum value in the dp array.

Code
def longest_increasing_subsequence(A):
    n = len(A)
    dp = [1]*n
    for i in range(n):
        for j in range(i):
            if A[i] > A[j] and A[i] != A[j]:
                dp[i] = max(dp[i], dp[j]+1)
    return max(dp)

A = [1, 2, 3, 4, 5]
print(longest_increasing_subsequence(A)) # Output: 5

A = [1, 2, 3, 4, 5, 5]
print(longest_increasing_subsequence(A)) # Output: 5

A = [5, 4, 3, 2, 1]
print(longest_increasing_subsequence(A)) # Output: 1
Explanation

In the given code, we first initialize the dp array with all values as 1. This is because the longest increasing subsequence ending at an index i can always have one element (i.e., A[i] itself).

We then loop through all indices in the array and for each i, we loop through all indices less than i and check whether the two conditions mentioned earlier are satisfied. If yes, we update the dp[i] value accordingly.

Finally, we return the maximum value in the dp array. The sample test cases are shown in the code snippet, and their expected outputs match the observed outputs.

Conclusion

This problem tests the knowledge of dynamic programming and how it can be used to solve the longest increasing subsequence problem with additional constraints. The given code provides a clear and concise solution to the problem.