Maximum Sum Subsequenc

You are given an array “NUMS” consisting of N integers and an integer, K. Your task is to determine the maximum sum of an increasing subsequence of length K.

Note:
1. The array may contain duplicate elements.
2. The array can also contain negative integers.
3. Every element of the subsequence must be greater than or equal to the previous element.

The subsequence of an array is a sequence of numbers that can be formed by deleting some or no elements without changing the order of the remaining elements. For example, if the given array “NUMS” = {1, 2, 5, 4, 8}, then {1, 2, 5, 4, 8}, {1, 5, 8}, {2} are some of the valid subsequences whereas the sequence {4, 2} is not a valid subsequence as the order of the elements differ from the original array.

Input Format:
The first line contains an integer T, which denotes the number of test cases or queries to be run. Then, the T test cases follow. 

The first line of each test case contains two space-separated integers N and K, denoting the number of elements in the array and the length of the subsequence to be considered.

The second line of each test case contains N space-separated integers, representing the elements of the array.
Output Format:
For each test case, print in a new line, an integer denoting the maximum sum of an increasing subsequence of length K.

Print “-1” if no such subsequence exists.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 500
1 <= K <= N
-10^9 <= NUMS[i] <= 10^9

Where NUMS[i] represents the i-th element of the array.

Time Limit: 1 sec
CodingNinjas
author
2y

This was a preety good DP-problem . I struggled a bit initially on finding the DP transition but on carefully observing the constraints of the problem , I figured that a O(N^2*K) DP solution will also...read more

CodingNinjas
author
2y
Naive Approach using Recursion

Approach: The approach is to find all subsequences of length ‘K’ using recursion and check whether it is increasing or not. If it is and its sum is more than the maximum ...read more

CodingNinjas
author
2y
Dynamic Programming

Approach: The approach is to use Dynamic Programming. We can create a DP table, and the value present at DP[i][j] will tell us the maximum sum that we can get for any increasing sub...read more

Add answer anonymously...
Amdocs Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter