Maximum sum increasing subsequence from a prefix and a given element after prefix is must

Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till i-th index and also including a given kth element which is after i, i.e., k > i .
Examples:

Input : arr[] = {1, 101, 2, 3, 100, 4, 5}
i-th index = 4 (Element at 4th index is 100)
K-th index = 6 (Element at 6th index is 5.)
Output : 11
So we need to calculate the maximum sum of subsequence (1 101 2 3 100 5) such that 5 is necessarily included in the subsequence, so answer is 11 by subsequence (1 2 3 5).

Input : arr[] = {1, 101, 2, 3, 100, 4, 5}
i-th index = 2 (Element at 2nd index is 2)
K-th index = 5 (Element at 5th index is 4.)
Output : 7
So we need to calculate the maximum sum of subsequence (1 101 2 4) such that 4 is necessarily included in the subsequence, so answer is 7 by subsequence (1 2 4).

Prerequisite : Maximum Sum Increasing Subsequence

Simple Approach:

  1. Construct a new array containing elements till ith index and the kth element.
  2. Recursively calculate all the increasing subsequences.
  3. Discard all the subsequences not having kth element included.
  4. Calculate the maximum sum from the left over subsequences and display it.

Time Complexity: O(2n)

Efficient Approach: Use a dynamic approach to maintain a table dp[][]. The value of dp[i][k] stores the maximum sum of increasing subsequence till ith index and containing the kth element.

Output:

11

Time Complexity: O(n2)

Note: This approach is very useful if you have to answer multiple such queries of i and k because using the pre calculated dp matrix you can answer such query in O(1) time.

To try similar problem, give this article a read: Maximum product of an increasing subsequence



My Personal Notes arrow_drop_up

Recommended Posts: