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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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
Updated on 09-Sep-2020 13:30:59