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 non-overlapping subarrays of length atmost K
Next article icon

Maximise array sum after taking non-overlapping sub-arrays of length K

Last Updated : 19 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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}, K = 2 
Output: 12 
Sub-arrays that maximizes sum will be {{1, 2}, {4, 5}}. 
Thus, the answer will be 12.
Input: arr[] = {1, 1, 1, 1, 1}, K = 1 
Output: 3 
 

 

Approach: This problem can be solved using 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 arr[i…n-1] satisfying above conditions. 
We will have two possible choices i.e. select the sub-array arr[i…i+k-1] and solve for dp[i + k + 1] or reject it and solve for dp[i + 1].
Thus, recurrence relation will be 
 

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

Since, the values of K can be large, we will use prefix-sum array to find the sum of all the elements of the sub-array arr[i…i + k – 1] in O(1). 
Overall, time complexity of the algorithm will be O(N).
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
#define maxLen 10
using namespace std;
 
// To store the states of dp
int dp[maxLen];
 
// To check if a given state
// has been solved
bool v[maxLen];
 
// To store the prefix-sum
int prefix_sum[maxLen];
 
// Function to fill the prefix_sum[] with
// the prefix sum of the given array
void findPrefixSum(int arr[], int n)
{
    prefix_sum[0] = arr[0];
    for (int i = 1; i < n; i++)
        prefix_sum[i] = arr[i] + prefix_sum[i - 1];
}
 
// 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 + k > n)
        return 0;
 
    // To check if a state has
    // been solved
    if (v[i])
        return dp[i];
    v[i] = 1;
 
    int x;
 
    if (i == 0)
        x = prefix_sum[k - 1];
    else
        x = prefix_sum[i + k - 1] - prefix_sum[i - 1];
 
    // Required recurrence relation
    dp[i] = max(maxSum(arr, i + 1, n, k),
                x + maxSum(arr, i + k + 1, n, k));
 
    // Returning the value
    return dp[i];
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 7, 6 };
    int n = sizeof(arr) / sizeof(int);
    int k = 1;
 
    // Finding prefix-sum
    findPrefixSum(arr, n);
 
    // Finding the maximum possible sum
    cout << maxSum(arr, 0, n, k);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    static int maxLen = 10;
 
    // To store the states of dp
    static int[] dp = new int[maxLen];
 
    // To check if a given state
    // has been solved
    static boolean[] v = new boolean[maxLen];
 
    // To store the prefix-sum
    static int[] prefix_sum = new int[maxLen];
 
    // Function to fill the prefix_sum[] with
    // the prefix sum of the given array
    static void findPrefixSum(int arr[], int n)
    {
        prefix_sum[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
            prefix_sum[i] = arr[i] + prefix_sum[i - 1];
        }
    }
 
    // 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 + k > n)
        {
            return 0;
        }
 
        // To check if a state has
        // been solved
        if (v[i])
        {
            return dp[i];
        }
        v[i] = true;
 
        int x;
 
        if (i == 0)
        {
            x = prefix_sum[k - 1];
        }
        else
        {
            x = prefix_sum[i + k - 1] - prefix_sum[i - 1];
        }
 
        // Required recurrence relation
        dp[i] = Math.max(maxSum(arr, i + 1, n, k),
                x + maxSum(arr, i + k + 1, n, k));
 
        // Returning the value
        return dp[i];
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {1, 3, 7, 6};
        int n = arr.length;
        int k = 1;
 
        // Finding prefix-sum
        findPrefixSum(arr, n);
 
        // Finding the maximum possible sum
        System.out.println(maxSum(arr, 0, n, k));
    }
}
 
// This code contributed by Rajput-Ji
 
 

Python3




# Python3 implementation of the approach
 
maxLen = 10
 
# To store the states of dp
dp = [0]*maxLen;
 
# To check if a given state
# has been solved
v = [0]*maxLen;
 
# To store the prefix-sum
prefix_sum = [0]*maxLen;
 
# Function to fill the prefix_sum[] with
# the prefix sum of the given array
def findPrefixSum(arr, n) :
 
    prefix_sum[0] = arr[0];
    for i in range(n) :
        prefix_sum[i] = arr[i] + prefix_sum[i - 1];
 
 
# Function to find the maximum sum subsequence
# such that no two elements are adjacent
def maxSum(arr, i, n, k) :
 
    # Base case
    if (i + k > n) :
        return 0;
 
    # To check if a state has
    # been solved
    if (v[i]) :
        return dp[i];
         
    v[i] = 1;
 
    if (i == 0) :
        x = prefix_sum[k - 1];
    else :
        x = prefix_sum[i + k - 1] - prefix_sum[i - 1];
 
    # Required recurrence relation
    dp[i] = max(maxSum(arr, i + 1, n, k),
                x + maxSum(arr, i + k + 1, n, k));
 
    # Returning the value
    return dp[i];
 
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 3, 7, 6 ];
     
    n = len(arr);
    k = 1;
 
    # Finding prefix-sum
    findPrefixSum(arr, n);
 
    # Finding the maximum possible sum
    print(maxSum(arr, 0, n, k));
     
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    static int maxLen = 10;
 
    // To store the states of dp
    static int[] dp = new int[maxLen];
 
    // To check if a given state
    // has been solved
    static bool[] v = new bool[maxLen];
 
    // To store the prefix-sum
    static int[] prefix_sum = new int[maxLen];
 
    // Function to fill the prefix_sum[] with
    // the prefix sum of the given array
    static void findPrefixSum(int []arr, int n)
    {
        prefix_sum[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
            prefix_sum[i] = arr[i] + prefix_sum[i - 1];
        }
    }
 
    // 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 + k > n)
        {
            return 0;
        }
 
        // To check if a state has
        // been solved
        if (v[i])
        {
            return dp[i];
        }
        v[i] = true;
 
        int x;
 
        if (i == 0)
        {
            x = prefix_sum[k - 1];
        }
        else
        {
            x = prefix_sum[i + k - 1] - prefix_sum[i - 1];
        }
 
        // Required recurrence relation
        dp[i] = Math.Max(maxSum(arr, i + 1, n, k),
                x + maxSum(arr, i + k + 1, n, k));
 
        // Returning the value
        return dp[i];
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {1, 3, 7, 6};
        int n = arr.Length;
        int k = 1;
 
        // Finding prefix-sum
        findPrefixSum(arr, n);
 
        // Finding the maximum possible sum
        Console.Write(maxSum(arr, 0, n, k));
    }
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
// Javascript implementation of the approach
var maxLen = 10
 
// To store the states of dp
var dp = Array(maxLen);
 
// To check if a given state
// has been solved
var v = Array(maxLen);
 
// To store the prefix-sum
var prefix_sum = Array(maxLen);;
 
// Function to fill the prefix_sum[] with
// the prefix sum of the given array
function findPrefixSum(arr, n)
{
    prefix_sum[0] = arr[0];
    for (var i = 1; i < n; i++)
        prefix_sum[i] = arr[i] + prefix_sum[i - 1];
}
 
// Function to find the maximum sum subsequence
// such that no two elements are adjacent
function maxSum(arr, i, n, k)
{
    // Base case
    if (i + k > n)
        return 0;
 
    // To check if a state has
    // been solved
    if (v[i])
        return dp[i];
    v[i] = 1;
 
    var x;
 
    if (i == 0)
        x = prefix_sum[k - 1];
    else
        x = prefix_sum[i + k - 1] - prefix_sum[i - 1];
 
    // Required recurrence relation
    dp[i] = Math.max(maxSum(arr, i + 1, n, k),
                x + maxSum(arr, i + k + 1, n, k));
 
    // Returning the value
    return dp[i];
}
 
// Driver code
var arr = [1, 3, 7, 6];
var n = arr.length;
var k = 1;
// Finding prefix-sum
findPrefixSum(arr, n);
// Finding the maximum possible sum
document.write( maxSum(arr, 0, n, k));
 
</script>
 
 
Output: 
9

 



Next Article
Maximum sum of non-overlapping subarrays of length atmost K

D

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

Similar Reads

  • Maximum sum of non-overlapping subarrays of length atmost K
    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 O
    10 min read
  • 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
  • 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
  • Minimum length of X[] after removing at most K sub-arrays
    Given an array X[] of length N and an integer K. Then your task is to output minimum length of X[] after removing at most K number of sub-arrays, which satisfies the following conditions: Size of the sub-array must be greater than 1.First and last element of sub-array must be same.Note: The sub-arra
    10 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
  • Maximum non overlapping Subset with sum greater than K
    Given an array, arr[] and integer K, the task is to find the maximum number of non-overlapping subsets such that the sum of the subsets is strictly greater than K when you may also change the value of each element to the maximum value of the particular subset. Examples: Input: arr[]= {90, 80, 70, 60
    5 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
  • K maximum sums of overlapping contiguous sub-arrays
    Given an array of Integers and an Integer value k, find out k sub-arrays(may be overlapping), which have k maximum sums. Examples: Input : arr = {4, -8, 9, -4, 1, -8, -1, 6}, k = 4 Output : 9 6 6 5Input : arr = {-2, -3, 4, -1, -2, 1, 5, -3}, k= 3 Output : 7 6 5 Using Kadane's Algorithm we can find t
    13 min read
  • Maximize maximum possible subarray sum of an array by swapping with elements from another array
    Given two arrays arr[] and brr[] consisting of N and K elements respectively, the task is to find the maximum subarray sum possible from the array arr[] by swapping any element from the array arr[] with any element of the array brr[] any number of times. Examples: Input: N = 5, K = 4, arr[] = { 7, 2
    7 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