Open In App

Maximum Subsequence sum with difference among consecutive numbers less than K

Last Updated : 01 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[], find the maximum sum that can be achieved by picking a subsequence such that the difference between consecutive elements in the subsequence is less than or equal to a given number ‘K’.

Examples:

Input: arr[] = {1, 8, 9, 4, 6, 7}, K = 2
Output: 24. 
Explanation: The maximum sum can be obtained by taking the subsequence {8, 9, 7}. As 8 + 9 + 7 = 24

Input: arr[] = {1, -2, 3, 14, 6, -17, 16, 25}, K = 5
Output: 30.
Explanation: The maximum sum can be obtained by taking the subsequence {14, 16}. As 14 + 16 = 30

Naive Approach: The Brute force approach to solve this problem is to generate all subsequences with no consecutive elements with differences greater than K. Then find the sum of all such subsequences and print the maximum sum. 

Time complexity: O(2n)
Auxiliary Space: O(1)

Efficient Approach: To solve the problem follow the below approach:

The idea to solve this problem is by using the concept of dynamic programming. In this approach, first, we initialize an array dp[] which stores the maximum sum ending at index i. Then we run a loop and for every index i, we have dp[i] as the sum of the current element arr[i] plus the maximum achievable sum in previous positions which has an absolute difference of less than or equal to k with arr[i].

Follow the steps involved in the approach:

  • Initialize a vector say dp of the size of the array that will store the maximum sum till index i, dp[i].
  • Initialize the base case, dp[0] with arr[0] as for a single element the maximum sum is the element itself.
  • Run a loop from i = 1 to i < n.
  • Initialize a variable say maxSum, that will store the maximum sum achievable so far.
  • For each index i, run a loop from j = i – 1 to j ? 0 and check if the difference between the current element and the previous element is less than or equal to K, arr[i] – arr[j] ? K.
  • If arr[i] – arr[j] ? K, update maxSum = max(maxSum, dp[j]). Here maxSum is the maximum sum achievable ending at the previous position.
  • Update dp[i] with the maximum sum, dp[i] = maxSum + arr[i].
  • In the last return the maximum element of the dp array which will be the maximum sum of subsequences with given conditions.

Below is the code for the above approach.

C++




// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
 
int max_sum_subseq(vector<int> arr, int k)
{
    int n = arr.size();
 
    // dp[i] stores the maximum sum
    // ending at index i
    vector<int> dp(n, 0);
    dp[0] = arr[0];
    for (int i = 1; i < n; i++) {
 
        // maxSum stores the maximum
        // sum achievable so far
        int maxSum = 0;
        for (int j = i - 1; j >= 0; j--) {
 
            // Check if difference between
            // arr[i] and arr[j] is less
            // than or equal to k
            if (abs(arr[i] - arr[j]) <= k) {
                maxSum = max(maxSum, dp[j]);
            }
        }
 
        // Update dp[i] with the maximum sum
        dp[i] = maxSum + arr[i];
    }
 
    // Return the maximum sum
    return *max_element(dp.begin(), dp.end());
}
 
// Drivers code
int main()
{
    vector<int> arr = { 1, 8, 9, 4, 6, 7 };
    int K = 2;
 
    // Function Call
    cout << "Maximum sum: " << max_sum_subseq(arr, K)
         << endl;
    return 0;
}


Java




// Java code for above approach
 
import java.util.*;
 
public class GFG {
 
    public static int max_sum_subseq(List<Integer> arr,
                                     int k)
    {
        int n = arr.size();
 
        // dp[i] stores the maximum sum
        // ending at index i
        int[] dp = new int[n];
        dp[0] = arr.get(0);
 
        for (int i = 1; i < n; i++) {
            // maxSum stores the maximum
            // sum achievable so far
            int maxSum = 0;
            for (int j = i - 1; j >= 0; j--) {
                // Check if difference between
                // arr[i] and arr[j] is less
                // than or equal to k
                if (Math.abs(arr.get(i) - arr.get(j))
                    <= k) {
                    maxSum = Math.max(maxSum, dp[j]);
                }
            }
            // Update dp[i] with the maximum sum
            dp[i] = maxSum + arr.get(i);
        }
        // Return the maximum sum
        return Arrays.stream(dp).max().getAsInt();
    }
 
    public static void main(String[] args)
    {
        List<Integer> arr = Arrays.asList(1, 8, 9, 4, 6, 7);
        int K = 2;
 
        // Function Call
        System.out.println("Maximum sum: "
                           + max_sum_subseq(arr, K));
    }
}


Python3




# Python code for above approach
def max_sum_subseq(arr, k):
    n = len(arr)
     
    # dp[i] stores the maximum sum
    # ending at index i
    dp = [0] * n
    dp[0] = arr[0]
    for i in range(1, n):
     
        # maxSum stores the maximum
        # sum achievable so far
        maxSum = 0
        for j in range(i-1, -1, -1):
     
            # Check if difference between
            # arr[i] and arr[j] is less
            # than or equal to k
            if abs(arr[i] - arr[j]) <= k:
                maxSum = max(maxSum, dp[j])
     
        # Update dp[i] with the maximum sum
        dp[i] = maxSum + arr[i]
     
    # Return the maximum sum
    return max(dp)
 
# Drivers code
arr = [1, 8, 9, 4, 6, 7]
K = 2
 
# Function Call
print("Maximum sum:", max_sum_subseq(arr, K))
 
# This code is contributed by Prasad Kandekar(prasad264)


C#




using System;
 
public class GFG {
  public static int max_sum_subseq(int[] arr, int k)
  {
    int n = arr.Length;
 
    // dp[i] stores the maximum sum
    // ending at index i
    int[] dp = new int[n];
    dp[0] = arr[0];
 
    for (int i = 1; i < n; i++)
    {
       
      // maxSum stores the maximum
      // sum achievable so far
      int maxSum = 0;
      for (int j = i - 1; j >= 0; j--)
      {
         
        // Check if difference between
        // arr[i] and arr[j] is less
        // than or equal to k
        if (Math.Abs(arr[i] - arr[j]) <= k) {
          maxSum = Math.Max(maxSum, dp[j]);
        }
      }
      // Update dp[i] with the maximum sum
      dp[i] = maxSum + arr[i];
    }
    // Return the maximum sum
    int maxi = Int32.MinValue;
    for (int i = 0; i < n; i++)
      maxi = Math.Max(maxi, dp[i]);
    return maxi;
  }
 
  // Driver Code
  static public void Main()
  {
    int[] arr = { 1, 8, 9, 4, 6, 7 };
    int K = 2;
 
    // Function Call
    Console.WriteLine("Maximum sum: "
                      + max_sum_subseq(arr, K));
  }
}
 
// This code is contributed by Rohit Pradhan


Javascript




// JavaScript code for above approach
 
function max_sum_subseq(arr, k) {
    let n = arr.length;
     
    // dp[i] stores the maximum sum
    // ending at index i
    let dp = new Array(n);
    dp[0] = arr[0];
     
    for (let i = 1; i < n; i++) {
        // maxSum stores the maximum
        // sum achievable so far
        let maxSum = 0;
        for (let j = i - 1; j >= 0; j--) {
            // Check if difference between
            // arr[i] and arr[j] is less
            // than or equal to k
            if (Math.abs(arr[i] - arr[j]) <= k) {
                maxSum = Math.max(maxSum, dp[j]);
            }
        }
        // Update dp[i] with the maximum sum
        dp[i] = maxSum + arr[i];
    }
    // Return the maximum sum
    return Math.max(...dp);  // ... is spread operator
}
 
let arr = [1, 8, 9, 4, 6, 7];
let K = 2;
 
// Function Call
console.log("Maximum sum: " + max_sum_subseq(arr, K));
 
// This code is contributed by karthik.


Output

Maximum sum: 24

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads