Skip to content
Related Articles

Related Articles

Improve Article

Find maximum Subsequence Sum according to given conditions

  • Last Updated : 12 Jun, 2021
Geek Week

Given an integer array nums and an integer K, The task is to find the maximum sum of a non-empty subsequence of the array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j – i <= K is satisfied.

A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. 


Input: nums = [10, 2, -10, 5, 20], K = 2
Output: 37
The subsequence is [10, 2, 5, 20].

Input: nums = [-1, -2, -3], K = 1
Output: -1

Input: nums = [10, -2, -10, -5, 20], K = 2
Output: 23



  • The optimal solution of this problem can be achieved by using the Sliding Window Maximum and Dynamic Programming .
  • At any index i after calculating the maximum sum for i, nums[i] will now store the maximum possible sum that can be obtained from a subsequence ending at i.
  • To calculate the maximum possible sum for every index i , check what is the maximum value that can be obtained from a window of size K before it. If the maximum value is negative, use zero instead.
  • To use the values of calculated sums optimally we use a deque to store the sums along with their indexes in an increasing order of the sums . We also pop the element from the back when its index goes out of the window k of current index i.


// C++ program to find the maximum sum
// subsequence under given constraint
#include <bits/stdc++.h>
using namespace std;
// Function return the maximum sum
int ConstrainedSubsetSum(vector<int>& nums,
                         int k)
    deque<pair<int, int> > d;
    // Iterating the given array
    for (int i = 0; i < nums.size(); i++)
        // Check if deque is empty
        nums[i] += d.size()
            ? max(d.back().first, 0) : 0;
        while (d.size() &&
               d.front().first < nums[i])
        d.push_front({ nums[i], i });
        if (d.back().second == i - k)
    int ans = nums[0];
    for (auto x : nums)
        ans = max(ans, x);
    return ans;
// Driver code
int main()
    vector<int> nums = { 10, -2, -10,
                        -5, 20 };
    int K = 2;
    // Function call
    cout << ConstrainedSubsetSum(nums, K)
        << endl;
    return 0;


Time Complexity: O(N) 
Space Complexity: O(K)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :