📜  门| GATE-CS-2005 |问题24(1)

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

GATE-CS-2005 Problem 24

This problem is a classic example of dynamic programming. We are given a sequence of n numbers and we need to find the maximum sum subsequence which is non-decreasing.

Problem Statement

Given a sequence of n numbers, the task is to find a subsequence of the given sequence such that the subsequence is non-decreasing and the sum of the subsequence is maximum. A subsequence is a sequence that can be derived from the given sequence by deleting some or no elements without changing the order of the remaining elements.

For example, consider the following sequence:

5 3 4 8 6 7

The maximum sum non-decreasing subsequence for this sequence is:

3 4 6 7
Solution

The key to solving this problem is to observe that the maximum sum non-decreasing subsequence that ends at a given index i can be computed from the maximum sum non-decreasing subsequence that ends at any previous index j < i. We can use this observation to build a dynamic programming solution.

Let f(i) be the maximum sum non-decreasing subsequence that ends at index i. Then we can compute f(i) as follows:

f(i) = max(f(j) + a(i)), for all j < i and a(j) <= a(i)

Here a(i) is the i-th element of the sequence. The above formula says that the maximum sum non-decreasing subsequence that ends at index i is the maximum of all possible subsequences that end at some previous index j < i, and have an element less than or equal to a(i).

The solution can be implemented using bottom-up dynamic programming. We start by computing f(1), then f(2), and so on, up to f(n). The final answer is the maximum of all f(i)'s.

def max_sum_non_decreasing_subsequence(seq):
    n = len(seq)
    f = [seq[i] for i in range(n)]

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

    return max(f)

seq = [5, 3, 4, 8, 6, 7]
print(max_sum_non_decreasing_subsequence(seq)) # Output: 18

The time complexity of the above solution is O(n^2), and the space complexity is O(n).