Given an integer array ‘arr’ of length N and an integer ‘k’, select some non-overlapping subarrays such that each sub-array if of length at most ‘k’, no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays are maximum.
Examples:
Input : arr[] = {-1, 2, -3, 4, 5}, k = 2
Output : 11
Sub-arrays that maximizes sum will be {{2}, {4, 5}}.
Thus, the answer will be 2+4+5 = 11.
Input :arr[] = {1, 1, 1, 1, 1}, k = 1
Output : 3
Naive Approach : A simple way is to generate all possible subsets of elements satisfying above conditions recursively and find the subset with maximum sum.
Time Complexity : O(2N)
Efficient Approach: A better approach is to use dynamic programming.
Let’s suppose we are at an index ‘i’.
Let dp[i] be defined as the maximum sum of elements of all possible subsets of sub-array {i, n-1} satisfying above conditions.
We will have ‘K+1’ possible choices i.e.
- Reject ‘i’ and solve for ‘i+1’.
- Select sub-array {i} and solve for ‘i+2’
- Select sub-array {i, i+1} and solve for ‘i+3’
.
.
k+1) Select sub-array {i, i+1, i+2, .., i+k-1} and solve for ‘i+k+1’.
Thus, recurrence relation will be:
dp[i] = max(dp[i+1], arr[i]+dp[i+2], arr[i]+arr[i+1]+dp[i+3],
...arr[i]+arr[i+1]+arr[i+2]...+arr[i+k-1] + dp[i+k+1])
Below is the implementation of the above approach:
C++
// C++ program to implement above approach #include <bits/stdc++.h> #define maxLen 10 using namespace std; // Variable to store states of dp int dp[maxLen]; // Variable to check if a given state has been solved bool visit[maxLen]; // Function to find the maximum sum subsequence // such that no two elements are adjacent int maxSum(int arr[], int i, int n, int k) { // Base case if (i >= n) return 0; // To check if a state has been solved if (visit[i]) return dp[i]; visit[i] = 1; // Variable to store // prefix sum for sub-array // {i, j} int tot = 0; dp[i] = maxSum(arr, i + 1, n, k); // Required recurrence relation for (int j = i; j < i + k and j < n; j++) { tot += arr[j]; dp[i] = max(dp[i], tot + maxSum(arr, j + 2, n, k)); } // Returning the value return dp[i]; } // Driver code int main() { // Input array int arr[] = { -1, 2, -3, 4, 5 }; int k = 2; int n = sizeof(arr) / sizeof(int); cout << maxSum(arr, 0, n, k); return 0; } |
Java
// Java program to implement above approach import java.io.*; class GFG { static int maxLen = 10; // Variable to store states of dp static int dp[] = new int[maxLen]; // Variable to check // if a given state has been solved static boolean []visit = new boolean[maxLen]; // Function to find the maximum sum subsequence // such that no two elements are adjacent static int maxSum(int arr[], int i, int n, int k) { // Base case if (i >= n) return 0; // To check if a state has been solved if (visit[i]) return dp[i]; visit[i] = true; // Variable to store // prefix sum for sub-array // {i, j} int tot = 0; dp[i] = maxSum(arr, i + 1, n, k); // Required recurrence relation for (int j = i; j < (i + k) && (j < n); j++) { tot += arr[j]; dp[i] = Math.max(dp[i], tot + maxSum(arr, j + 2, n, k)); } // Returning the value return dp[i]; } // Driver code public static void main (String[] args) { // Input array int arr[] = { -1, 2, -3, 4, 5 }; int k = 2; int n = arr.length; System.out.println(maxSum(arr, 0, n, k)); } } // This code is contributed by ajit. |
Python3
# Python3 program to implement above approach maxLen = 10 # Variable to store states of dp dp = [0]*maxLen; # Variable to check if a given state has been solved visit = [0]*maxLen; # Function to find the maximum sum subsequence # such that no two elements are adjacent def maxSum(arr, i, n, k) : # Base case if (i >= n) : return 0; # To check if a state has been solved if (visit[i]) : return dp[i]; visit[i] = 1; # Variable to store # prefix sum for sub-array # {i, j} tot = 0; dp[i] = maxSum(arr, i + 1, n, k); # Required recurrence relation j = i while (j < i + k and j < n) : tot += arr[j]; dp[i] = max(dp[i], tot + maxSum(arr, j + 2, n, k)); j += 1 # Returning the value return dp[i]; # Driver code if __name__ == "__main__" : # Input array arr = [ -1, 2, -3, 4, 5 ]; k = 2; n = len(arr); print(maxSum(arr, 0, n, k)); # This code is contributed by AnkitRai01 |
C#
// C# program to implement above approach using System; class GFG { static int maxLen = 10; // Variable to store states of dp static int []dp = new int[maxLen]; // Variable to check // if a given state has been solved static bool []visit = new bool[maxLen]; // Function to find the maximum sum subsequence // such that no two elements are adjacent static int maxSum(int []arr, int i, int n, int k) { // Base case if (i >= n) return 0; // To check if a state has been solved if (visit[i]) return dp[i]; visit[i] = true; // Variable to store // prefix sum for sub-array // {i, j} int tot = 0; dp[i] = maxSum(arr, i + 1, n, k); // Required recurrence relation for (int j = i; j < (i + k) && (j < n); j++) { tot += arr[j]; dp[i] = Math.Max(dp[i], tot + maxSum(arr, j + 2, n, k)); } // Returning the value return dp[i]; } // Driver code static public void Main () { // Input array int []arr = { -1, 2, -3, 4, 5 }; int k = 2; int n = arr.Length; Console.WriteLine (maxSum(arr, 0, n, k)); } } // This code is contributed by ajit. |
11
Time Complexity: O(n*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.
Recommended Posts:
- Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
- Maximum length L such that the sum of all subarrays of length L is less than K
- Maximize the maximum subarray sum after removing atmost one element
- Queries to find maximum sum contiguous subarrays of given length in a rotating array
- Length of the longest subsegment which is UpDown after inserting atmost one integer
- Length of Longest Subarray with same elements in atmost K increments
- Find the length of the longest subarray with atmost K occurrences of the integer X
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Min and max length subarray having adjacent element difference atmost K
- Count of subsequences of length atmost K containing distinct prime elements
- Maximum XOR value of maximum and second maximum element among all possible subarrays
- Maximum number of fixed points using atmost 1 swap
- Maximum average of a subarray of size of atleast X and atmost Y
- Maximum GCD of all subarrays of length at least 2
- Longest Subarray having sum of elements atmost 'k'
- Maximize sum of atmost K elements in array by taking only corner elements | Set 2
- Longest Increasing Subsequence having sum value atmost K
- Differences between number of increasing subarrays and decreasing subarrays in k sized windows
- Make sum of all subarrays of length K equal by only inserting elements
- Generate a unique Array of length N with sum of all subarrays divisible by N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

