Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Maximum sum of at most K non-overlapping Subarray
Next article icon

Maximum sum of non-overlapping subarrays of length atmost K

Last Updated : 19 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
 

  1. Reject ‘i’ and solve for ‘i+1’.
  2. Select sub-array {i} and solve for ‘i+2’
  3. Select sub-array {i, i+1} and solve for ‘i+3’

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.
 
 

Javascript




<script>
    // Javascript program to implement above approach
     
    let maxLen = 10;
   
    // Variable to store states of dp
    let dp = new Array(maxLen);
 
    // Variable to check
    // if a given state has been solved
    let visit = new Array(maxLen);
 
    // Function to find the maximum sum subsequence
    // such that no two elements are adjacent
    function 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] = true;
 
        // Variable to store
        // prefix sum for sub-array
        // {i, j}
        let tot = 0;
        dp[i] = maxSum(arr, i + 1, n, k);
 
        // Required recurrence relation
        for (let 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];
    }
     
    // Input array
    let arr = [ -1, 2, -3, 4, 5 ];
       
    let k = 2;
       
    let n = arr.length;
       
    document.write(maxSum(arr, 0, n, k));
 
</script>
 
 
Output: 
11

 

Time Complexity: O(n*k) 
 Space complexity: O(n)

Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a 1D DP of size n to store the solution of the subproblems.
  • Initialize the DP  with 0.
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
  • Create a variable res and to store the final result and update it by iterating through Dp. 
  • Return the final solution stored in res

Implementation :

C++




#include <bits/stdc++.h>
#define maxLen 10
using namespace std;
 
 
// Function to find the maximum sum subsequence
// such that no two elements are adjacent
int maxSum(int arr[], int n, int k)
{
    // DP table
    int dp[n];
     
    // Initializing the DP table
    memset(dp, 0, sizeof(dp));
     
    // Computing the DP table
    for (int i = 0; i < n; i++) {
        int tot = 0;
        for (int j = i - k; j < i; j++) {
            if (j >= 0)
                tot = max(tot, dp[j]);
        }
        dp[i] = tot + arr[i];
    }
     
    // Returning the maximum sum
    int res = 0;
    for (int i = 0; i < n; i++)
        res = max(res, dp[i]);
         
    // return final ans
    return res;
}
 
// 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, n, k);
     
    return 0;
}
 
 

Java




import java.util.Arrays;
 
class GFG
{
   
    // Function to find the maximum sum subsequence
    // such that no two elements are adjacent
    static int maxSum(int arr[], int n, int k)
    {
       
        // DP table
        int dp[] = new int[n];
 
        // Initializing the DP table
        Arrays.fill(dp, 0);
 
        // Computing the DP table
        for (int i = 0; i < n; i++) {
            int tot = 0;
            for (int j = i - k; j < i; j++) {
                if (j >= 0)
                    tot = Math.max(tot, dp[j]);
            }
            dp[i] = tot + arr[i];
        }
 
        // Returning the maximum sum
        int res = 0;
        for (int i = 0; i < n; i++)
            res = Math.max(res, dp[i]);
 
        // return final ans
        return res;
    }
 
    // 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, n, k));
    }
}
 
 

Python3




def maxSum(arr, n, k):
    # DP table
    dp = [0] * n
 
    # Computing the DP table
    for i in range(n):
        tot = 0
        for j in range(i - k, i):
            if j >= 0:
                tot = max(tot, dp[j])
        dp[i] = tot + arr[i]
 
    # Returning the maximum sum
    res = 0
    for i in range(n):
        res = max(res, dp[i])
 
    # return final ans
    return res
 
 
# Driver code
arr = [-1, 2, -3, 4, 5]
k = 2
n = len(arr)
print(maxSum(arr, n, k))
 
 

C#




using System;
 
class MaxSum
{
    static int ComputeMaxSum(int[] arr, int n, int k)
    {
        // DP table
        int[] dp = new int[n];
 
        // Computing the DP table
        for (int i = 0; i < n; i++)
        {
            int tot = 0;
            for (int j = i - k; j < i; j++)
            {
                if (j >= 0)
                {
                    tot = Math.Max(tot, dp[j]);
                }
            }
            dp[i] = tot + arr[i];
        }
 
        // Returning the maximum sum
        int res = 0;
        for (int i = 0; i < n; i++)
        {
            res = Math.Max(res, dp[i]);
        }
 
        // return final ans
        return res;
    }
 
    static void Main()
    {
        int[] arr = {-1, 2, -3, 4, 5};
        int k = 2;
        int n = arr.Length;
        Console.WriteLine(ComputeMaxSum(arr, n, k));
    }
}
 
 

Javascript




// Function to find the maximum sum subsequence
// such that no two elements are adjacent
function maxSum(arr, n, k)
{
    // DP table
    let dp = new Array(n);
     
    // Initializing the DP table
    dp.fill(0);
     
    // Computing the DP table
    for (let i = 0; i < n; i++) {
        let tot = 0;
        for (let j = i - k; j < i; j++) {
            if (j >= 0)
                tot = Math.max(tot, dp[j]);
        }
        dp[i] = tot + arr[i];
    }
     
    // Returning the maximum sum
    let res = 0;
    for (let i = 0; i < n; i++)
        res = Math.max(res, dp[i]);
         
    // return final ans
    return res;
}
 
// Driver code
function main()
{
    // Input array
    let arr = [ -1, 2, -3, 4, 5 ];
     
    let k = 2;
     
    let n = arr.length;
     
    console.log(maxSum(arr, n, k));
}
 
main();
 
 

Output

11

Time Complexity: O(n*k) 
Auxiliary Space: O(n)



Next Article
Maximum sum of at most K non-overlapping Subarray

D

DivyanshuShekhar1
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • Recursion
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Recursion

Similar Reads

  • Maximum Sum of two non-overlapping Subarrays of any length
    Given an array A consisting of N integers, the task is to find the maximum sum of two non-overlapping subarrays of any length of the array. Note: You can select empty subarrays also. Examples: Input: N = 3, A[] = {-4, -5, -2}Output: 0Explanation: Two empty subarrays are optimal with maximum sum = 0.
    6 min read
  • Maximum sum of lengths of non-overlapping subarrays with k as the max element.
    Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element. Examples: Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4} k = 4 Output : 5 {2, 1, 4} => Length = 3 {3, 4} => Length = 2 So, 3 + 2 = 5 is the answer Input : arr[] = {1, 2, 3, 2, 3, 4, 1
    15+ min read
  • Maximum sum of at most K non-overlapping Subarray
    Given an array, arr[] of size N, the task is to find the sum of the at most K non-overlapping contiguous subarray within an arr[] with the maximum sum. Examples: Input: arr[] = [4, 1, -3, 7, -5, 6, -2, 1], K = 3Output: 18Explanation: In the above input, the maximum k subarray sum is 18 and the subar
    15 min read
  • Max sum of M non-overlapping subarrays of size K
    Given an array and two numbers M and K. We need to find the max sum of sums of M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array si
    15+ min read
  • Maximize count of non-overlapping subarrays with sum K
    Given an array arr[] and an integer K, the task is to print the maximum number of non-overlapping subarrays with a sum equal to K. Examples: Input: arr[] = {-2, 6, 6, 3, 5, 4, 1, 2, 8}, K = 10Output: 3Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2,
    6 min read
  • Count maximum non-overlapping subarrays with given sum
    Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
    7 min read
  • Maximum sum two non-overlapping subarrays of given size
    Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of
    12 min read
  • K maximum sums of non-overlapping contiguous sub-arrays
    Given an Array of Integers and an Integer value k, find out k non-overlapping sub-arrays which have k maximum sums. Examples: Input : arr1[] = {4, 1, 1, -1, -3, -5, 6, 2, -6, -2}, k = 3. Output : {4,1},{1} and {6,2} can be taken, thus the output should be 14. Input : arr2 = {5, 1, 2, -6, 2, -1, 3, 1
    10 min read
  • Maximise array sum after taking non-overlapping sub-arrays of length K
    Given an integer array arr[] of length N and an integer K, the task is to select some non-overlapping sub-arrays such that each sub-array is exactly of length K, no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays is maximum.Examples: Input: arr[] = {1, 2, 3, 4, 5},
    8 min read
  • Maximum sum of subarrays having distinct elements of length K
    Given an array, arr[] and a value k, represent the length of the subarray to be considered. Find the maximum sum that can be obtained from the subarray of length k such that each element of the subarray is unique. If there is no subarray that meets the required condition then return 0. Examples: Inp
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences