Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array in C++ program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n and an integer k. Our task is to create a program to find the maximum sum possible for a subsequence such that no two elements appear at a distance < K in the array.

Problem Description − We need to find the maximum sum of sub−seqeunce that considers elements that are k distance from each other.

Let’s take an example to understand the problem,

Input

arr[] = {6, 2, 5, 1, 9, 11, 4} k = 2

Output

16

Explanation

All possible sub−sequences of elements that differ by k or more.
{6, 1, 4}, sum = 11
{2, 9}, sum = 11
{5, 11}, sum = 16
{1, 4}, sum = 5
...
maxSum = 16

Solution Approach

A solution to the problem is using dynamic programming. For the solution, we will be finding the maximum possible sum until the current element of the array. And store it into DP[i], for this we will find the max possible sum. For i-th index, we need to check if adding the current index value increases the sub−sequence sum or not.

if( DP[i − (k+1)] + arr[i] > DP[i − 1] )
−> DP[i] = DP[i − (k+1)] + arr[i]
otherwise DP[i] = DP[i−1]

The maximum element of the dynamic array gives the max subsequence sum.

Algorithm

Initialize

maxSumSubSeq = −1, maxSumDP[n]

Step 1

Initialize maxSumDP[0] = arr[0]

Step 2

Loop for i −> 1 to n.

Step 2.1

if i < k −> maxSumDP[i] = maximum of arr[i] or
maxSumDP[i− 1].

Step 2.2

else, maxSumDP[i] = maximum of arr[i] or maxSumDP[i − (k + 1)] + arr[i].

Step 3

Find the maximum value of all elements from maxSumDP and store
it to maxSumSubSeq.

Step 4

Return maxSumSubSeq

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int retMaxVal(int a, int b){
   if(a > b)
   return a;
   return b;
}
int calcMaxSumSubSeq(int arr[], int k, int n) {
   int maxSumDP[n];
   int maxSum = −1;
   maxSumDP[0] = arr[0];
   for (int i = 1; i < n; i++){
      if(i < k ){
         maxSumDP[i] = retMaxVal(arr[i], maxSumDP[i − 1]);
      }
      else
      maxSumDP[i] = retMaxVal(arr[i], maxSumDP[i − (k +
      1)] + arr[i]);
   }
   for(int i = 0; i < n; i++)
   maxSum = retMaxVal(maxSumDP[i], maxSum);
   return maxSum;
}
int main() {
   int arr[] = {6, 2, 5, 1, 9, 11, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 2;
   cout<<"The maximum sum possible for a sub−sequence such
   that no two elements appear at a distance < "<<k<<" in the array is "<<calcMaxSumSubSeq(arr, k, n);
   return 0;
}

Output

The maximum sum possible for a sub−sequence such that no two
elements appear at a distance < 2 in the array is 16
raja
Published on 09-Dec-2020 13:37:08
Advertisements