Was it helpful?

Question


In this tutorial, we will be discussing a program to find maximum sum subsequence with at-least k distant elements.

For this we will be provided with an array containing integers and a value K. Our task is to find the subsequence having maximum sum such that all the elements are at least K elements apart.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//finding maximum sum subsequence
int maxSum(int arr[], int N, int k) {
   int MS[N];
   MS[N - 1] = arr[N - 1];
   for (int i = N - 2; i >= 0; i--) {
      if (i + k + 1 >= N)
         MS[i] = max(arr[i], MS[i + 1]);
      else
         MS[i] = max(arr[i] + MS[i + k + 1], MS[i + 1]);
   }
   return MS[0];
}
int main() {
   int N = 10, k = 2;
   int arr[] = { 50, 70, 40, 50, 90, 70, 60, 40, 70, 50 };
   cout << maxSum(arr, N, k);
   return 0;
}

Output

230
raja
Published on 09-Sep-2020 13:30:59

Was it helpful?
Not affiliated with Tutorialspoint
scroll top