Maximum sum subsequence with at-least k distant elements in C++ program

In this problem, we are given an array arr[] of size n and a number k. Our task is to create a program to find the maximum sum subsequence with atleast k distant elements.

Problem Description − We need to find the sum of subarrays such that the elements of the subarray are taken from the array whose index is at k distance and the sum is maximized.

Let’s take an example to understand the problem,


arr[] = {2, 3, 7, 9, 2, 8, 3}




All subsequences that satisfy the given condition,
{2, 9, 3}, Sum = 14
{3, 2}, Sum = 5
{7, 8}, Sum = 15

Solution Approach

A simple solution to the problem is by finding all possible subarrays that satisfy the given condition. Find the sum of all arrays and return the maximum of all.

A more efficient solution to the problem is by using a dynamic programming approach by creating an array to store the maximum sum until the current element. For the current element, we can either consider it for the sum or discard it for the sum, taking whichever increases the sum till the current index.

If we consider it for the sum, sum[i] = sum[i + k + 1] + arr[i+1] Otherwise discard it for the sum, sum[i] = sum[i+1] And at the end return the maximum sum which is at the sum[0].


Program to illustrate the working of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int calcMaxSubSeqSum(int arr[], int N, int k){
   int maxSumDP[N];
   maxSumDP[N − 1] = arr[N − 1];
   for (int i = N − 2; i >= 0; i−−) {
      if (i + k + 1 >= N)
         maxSumDP[i] = max(arr[i], maxSumDP[i + 1]);
         maxSumDP[i] = max(arr[i] + maxSumDP[i + k + 1], maxSumDP[i + 1]);
   return maxSumDP[0];
int main() {
   int N = 10, k = 2;
   int arr[] = { 50, 70, 40, 50, 90, 70, 60, 40, 70, 50 };
   cout<<"The maximum sum subsequence with at−least k distant elements is "<<calcMaxSubSeqSum(arr, N, k);
   return 0;


The maximum sum subsequence with at-least k distant elements is 230

Updated on: 09-Dec-2020


Kickstart Your Career

Get certified by completing the course

Get Started