Open In App

Maximum subsequence sum with adjacent elements having atleast K difference in index

Last Updated : 10 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of integers of length N and an integer K (1 ? k ? N), the task is to find the maximum subsequence sum in the array such that adjacent elements in that subsequence have at least a difference of K in their indices in the original array.

Examples: 

Input: arr[] = {1, 2, -2, 4, 3, 1}, K = 4 
Output:
Explanation: 
Such Subsequences that can be selected: {1, 3}, {1, 1}, {2, 1} 
Subsequence with maximum sum = (1 + 3) = 4 
Selected elements are a[0] and a[4] (difference between indices = 4)

Input: arr[] = {1, 2, 72, 4, 3}, K = 2 
Output: 76 
Explanation: 
Such Subsequences that can be selected – {{1, 72, 3}, {2, 4}, {2, 3}, {1, 4}, {1, 3}} 
Subsequence with maximum sum = (1 + 72 + 3) = 76 
Selected elements are a[0], a[2] and a[4] (difference between each indices = 2) 
 

Naive approach: Generate all possible subsets of the array and check for each of the subsets that it satisfies the condition such that two adjacent elements have at least a difference of K in their indices. If yes, then compare its sum with the largest sum obtained till now and update the sum if it is greater than the obtained sum till now.
Efficient Approach: This problem can be solved using Dynamic Programming. In which for each element in array consider such that if we take this element then is it contributes into the final sum obtained If yes then add it into the DP array for that element.

Let’s decide the states of ‘dp’. Let dp[i] be the largest possible sum for the sub-array starting from index ‘0’ and ending at index ‘i’. Now, we have to find a recurrence relation between this state and a lower-order state.
Now the Recurrence Relation for the array will have two choices for every index i.

  • Choose the current index: 
    In this case, the element that can be chosen is at index i-k. 
    So,
dp[i] = arr[i] + dp[i - k]
  • Skip the current Index. 
    In this case, the element that can be chosen is at index i-1. 
    So,
dp[i] = dp[i - 1]

For every index choose that condition that gives the maximum sum at that index, So the final recurrence relation will be: 

dp[i] = max(dp[i – 1], arr[i] + dp[i – k]) 
 

Below is the implementation of the above approach. 

C++




// C++ implementation to find the
// maximum sum subsequence such that
// two adjacent element have atleast
// difference of K in their indices
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum
// between two elements a and b
int maxi(int a, int b)
{
    if (a > b) {
        return a;
    }
    else {
        return b;
    }
}
 
// Function to find the maximum sum
// subsequence such that two adjacent
// element have atleast difference
// of K in their indices
int max_sum(int arr[], int n, int k)
{
    // DP Array to store the maximum
    // sum obtained till now
    int dp[n];
 
    // Either select the first element
    // or Nothing
    dp[0] = maxi(0, arr[0]);
    int i = 1;
 
    // Either Select the (i - 1) element
    // or let the previous best answer be
    // the current best answer
    while (i < k) {
        dp[i] = maxi(dp[i - 1], arr[i]);
        i++;
    }
    i = k;
 
    // Either select the best sum
    // till previous_index or select the
    // current element + best_sum till index-k
    while (i < n) {
        dp[i] = maxi(dp[i - 1], arr[i] + dp[i - k]);
        i++;
    }
    return dp[n - 1];
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, -2, 4, 3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    cout << max_sum(arr, n, k);
    return 0;
}


Java




// Java implementation to find the
// maximum sum subsequence such that
// two adjacent element have atleast
// difference of K in their indices
class GFG
{
 
    // Function to find the maximum sum
    // subsequence such that two adjacent
    // element have atleast difference
    // of K in their indices
    static int max_sum(int arr[], int n, int k)
    {
        // DP Array to store the maximum
        // sum obtained till now
        int dp[] = new int[n];
     
        // Either select the first element
        // or Nothing
        dp[0] = Math.max(0, arr[0]);
        int i = 1;
     
        // Either Select the (i - 1) element
        // or let the previous best answer be
        // the current best answer
        while (i < k)
        {
            dp[i] = Math.max(dp[i - 1], arr[i]);
            i++;
        }
        i = k;
     
        // Either select the best sum
        // till previous_index or select the
        // current element + best_sum till index-k
        while (i < n)
        {
            dp[i] = Math.max(dp[i - 1],
                    arr[i] + dp[i - k]);
            i++;
        }
        return dp[n - 1];
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int arr[] = { 1, 2, -2, 4, 3, 1 };
        int n = arr.length;
        int k = 4;
        System.out.println(max_sum(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation to find the
# maximum sum subsequence such that
# two adjacent element have atleast
# difference of K in their indices
 
# Function to find the maximum sum
# subsequence such that two adjacent
# element have atleast difference
# of K in their indices
def max_sum(arr, n, k) :
 
    # DP Array to store the maximum
    # sum obtained till now
    dp = [0] * n;
 
    # Either select the first element
    # or Nothing
    dp[0] = max(0, arr[0]);
    i = 1;
 
    # Either Select the (i - 1) element
    # or let the previous best answer be
    # the current best answer
    while (i < k) :
        dp[i] = max(dp[i - 1], arr[i]);
        i += 1;
 
    i = k;
 
    # Either select the best sum
    # till previous_index or select the
    # current element + best_sum till index-k
    while (i < n) :
        dp[i] = max(dp[i - 1], arr[i] + dp[i - k]);
        i += 1;
     
    return dp[n - 1];
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 1, 2, -2, 4, 3, 1 ];
    n = len(arr)
    k = 4;
    print(max_sum(arr, n, k));
 
# This code is contributed by AnkitRai01


C#




// C# implementation to find the
// maximum sum subsequence such that
// two adjacent element have atleast
// difference of K in their indices
using System;
 
class GFG
{
 
    // Function to find the maximum sum
    // subsequence such that two adjacent
    // element have atleast difference
    // of K in their indices
    static int max_sum(int []arr, int n, int k)
    {
        // DP Array to store the maximum
        // sum obtained till now
        int []dp = new int[n];
     
        // Either select the first element
        // or Nothing
        dp[0] = Math.Max(0, arr[0]);
        int i = 1;
     
        // Either Select the (i - 1) element
        // or let the previous best answer be
        // the current best answer
        while (i < k)
        {
            dp[i] = Math.Max(dp[i - 1], arr[i]);
            i++;
        }
        i = k;
     
        // Either select the best sum
        // till previous_index or select the
        // current element + best_sum till index-k
        while (i < n)
        {
            dp[i] = Math.Max(dp[i - 1],
                    arr[i] + dp[i - k]);
            i++;
        }
        return dp[n - 1];
    }
     
    // Driver Code
    public static void Main()
    {
        int []arr = { 1, 2, -2, 4, 3, 1 };
        int n = arr.Length;
        int k = 4;
        Console.WriteLine(max_sum(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// javascript implementation to find the
// maximum sum subsequence such that
// two adjacent element have atleast
// difference of K in their indices
 
// Function to find the maximum sum
// subsequence such that two adjacent
// element have atleast difference
// of K in their indices
function max_sum(arr , n , k)
{
    // DP Array to store the maximum
    // sum obtained till now
    var dp = Array.from({length: n}, (_, i) => 0);
 
    // Either select the first element
    // or Nothing
    dp[0] = Math.max(0, arr[0]);
    var i = 1;
 
    // Either Select the (i - 1) element
    // or let the previous best answer be
    // the current best answer
    while (i < k)
    {
        dp[i] = Math.max(dp[i - 1], arr[i]);
        i++;
    }
    i = k;
 
    // Either select the best sum
    // till previous_index or select the
    // current element + best_sum till index-k
    while (i < n)
    {
        dp[i] = Math.max(dp[i - 1],
                arr[i] + dp[i - k]);
        i++;
    }
    return dp[n - 1];
}
 
// Driver Code
var arr = [ 1, 2, -2, 4, 3, 1 ];
var n = arr.length;
var k = 4;
document.write(max_sum(arr, n, k));
 
// This code is contributed by 29AjayKumar
</script>


Output: 

4

 

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



Similar Reads

Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Maximum adjacent index difference for a subsequence T present in given string S
Given two strings S and T of lengths n and m respectively. Find the maximum adjacent index difference for the indices where string T is present in string S as a subsequence. Cost is defined as the difference between indices of subsequence TThe maximum cost of a sequence is defined as max(ai+1−ai) for 1 ≤ i &lt; m.It is guaranteed that there is at l
7 min read
Cost of creating smallest subsequence with sum of difference between adjacent elements maximum
Given two array of N integers arr[] and costArray[], representing removal cost associated with each element. The task is to find the subsequence from the given array of minimum cost such that the sum of the difference between adjacent elements is maximum. On removing each element, cost is incurred.Examples: Input: N = 3, arr[] = { 3, 2, 1 }, costAr
10 min read
Longest non-decreasing subsequence having difference between adjacent elements less than D
Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D. Examples: Input: arr[] = {1, 3, 2, 4, 5}, D = 2Output: 3Explanation:Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the
6 min read
Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
Given two arrays A[] and B[], and an integer K, the task is to find the number of ways to select two subarrays of the same size, one from A and the other one from B such that the subarrays have at least K equal pairs of elements. (i.e. the number of pairs (A[i], B[j]) in the two selected subarrays such that A[i] = B[j] &gt;= K). Examples: Input: A[
13 min read
Maximum sum of a subsequence having difference between their indices equal to the difference between their values
Given an array A[] of size N, the task is to find the maximum sum of a subsequence such that for each pair present in the subsequence, the difference between their indices in the original array is equal to the difference between their values. Examples: Input: A[] = {10, 7, 1, 9, 10, 15}, N = 6Output: 26Explanation: Subsequence: {7, 9, 10}. Indices
5 min read
Find maximum difference between elements having a fixed index difference of K
Given an integer K and an unsorted array of integers arr[], find the maximum difference between elements in the array having a fixed index difference of K. Examples: Input: arr[] = [2, 9, 7, 4, 6, 8, 3], K = 2Output: 5Explanation: The maximum absolute difference with an index difference of two is 5, which occurs between arr[0] and arr[2] Input: arr
5 min read
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right
Given an array, arr[] size N, the task is to find the smallest index of the array such that the sum of all the array elements on the left side of the index is equal to the reverse of the digits of the sum of all the array elements on the right side of that index. If no such index is found then print -1. Examples: Input: arr[] = { 5, 7, 3, 6, 4, 9,
18 min read
Maximum subsequence sum of at most K-distant adjacent elements
Given an array arr[] consisting of integers of length N and an integer K (1 &lt;= K &lt;= N), the task is to find the maximum sub-sequence sum in the array such that adjacent elements in that sub-sequence have at most a difference of K in their indices in the original array. In other words, if i and j are indices of two consecutive elements of sub-
10 min read
Queries to find longest subsequence having no similar adjacent elements with updates
Given an array arr[] consisting of N integers and an array Queries[][] with each query of the form {x, y}. For each query, the task is to replace the element at index x ( 1-based indexing ) by y and find the length of the longest subsequence having no similar adjacent elements. Examples: Input: arr[] = {1, 1, 2, 5, 2}, Q = 2, Queries[][] = {{1, 3},
14 min read