Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum sum subsequence with at-least k distant elements in C++
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
#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
Advertisements