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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum sum two non-overlapping subarrays of given size
Next article icon

Maximum sum subarray of size range [L, R]

Last Updated : 08 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[] of size N and two integer L and R. The task is to find the maximum sum subarray of size between L and R (both inclusive).

Example: 

Input: arr[] = {1, 2, 2, 1}, L = 1, R = 3 
Output: 5 
Explanation: 
Subarray of size 1 are {1}, {2}, {2}, {1} and maximum sum subarray = 2 for subarray {2}. 
Subarray of size 2 are {1, 2}, {2, 2}, {2, 1}, and maximum sum subarray = 4 for subarray {2, 2}. 
Subarray of size 3 are {1, 2, 2}, {2, 2, 1}, and maximum sum subarray = 5 for subarray {2, 2, 1}. 
Hence the maximum possible sum subarray is 5.

Input: arr[] = {-1, -3, -7, -11}, L = 1, R = 4 
Output: -1 

Approach: 

  • Here we will use the concept of sliding window which is discuss in this post.
  • First calculate prefix sum of array in array pre[].
  • Next iterate over the range L to N -1, and consider all subarray of size L to R.
  • Create a multiset for storing prefix sums of subarray length L to R.
  • Now to find maximum sum subarray ending at index i just subtract pre[i] and minimum of all values from pre[i – L] to pre[i – R].
  • Finally return maximum of all sums.

Below is the implementation of the above approach:

C++




// C++ program to find Maximum sum
// subarray of size between L and R.
 
#include <bits/stdc++.h>
using namespace std;
 
// function to find Maximum sum subarray
// of size between L and R
void max_sum_subarray(vector<int> arr,
                      int L, int R)
{
    int n = arr.size();
    int pre[n] = { 0 };
 
    // calculating prefix sum
    pre[0] = arr[0];
    for (int i = 1; i < n; i++) {
        pre[i] = pre[i - 1] + arr[i];
    }
    multiset<int> s1;
 
    // maintain 0 for initial
    // values of i upto R
    // Once i = R, then
    // we need to erase that 0 from
    // our multiset as our first
    // index of subarray
    // cannot be 0 anymore.
    s1.insert(0);
    int ans = INT_MIN;
 
    ans = max(ans, pre[L - 1]);
 
    // we maintain flag to
    // counter if that initial
    // 0 was erased from set or not.
    int flag = 0;
 
    for (int i = L; i < n; i++) {
 
        // erase 0 from multiset once i=b
        if (i - R >= 0) {
            if (flag == 0) {
 
                auto it = s1.find(0);
                s1.erase(it);
                flag = 1;
            }
        }
        // insert pre[i-L]
        if (i - L >= 0)
            s1.insert(pre[i - L]);
 
        // find minimum value in multiset.
        ans = max(ans,
                  pre[i] - *s1.begin());
 
        // erase pre[i-R]
        if (i - R >= 0) {
            auto it = s1.find(pre[i - R]);
            s1.erase(it);
        }
    }
    cout << ans << endl;
}
 
// Driver code
int main()
{
    int L, R;
    L = 1;
    R = 3;
    vector<int> arr = { 1, 2, 2, 1 };
    max_sum_subarray(arr, L, R);
    return 0;
}
 
 

Java




// Java program to find Maximum sum
// subarray of size between L and R.
import java.util.*;
class GFG {
// function to find Maximum sum subarray
// of size between L and R
static void max_sum_subarray(List<Integer> arr, int L, int R){
     
    int n = arr.size();
    int[] pre = new int[n + 1];
 
    // calculating prefix sum
    // here pre[0] = 0
    for (int i = 1; i <= n; i++) {
        pre[i] = pre[i - 1]+arr.get(i - 1);
    }   
     
      // treemap for storing prefix sums for
      // subarray length L to R
    TreeMap<Integer, Integer> s1 = new TreeMap<>();
 
    int ans = Integer.MIN_VALUE;
 
    for (int i = L; i <= n; i++) {
         
        // if i > R, erase pre[i - R - 1]
        // note that pre[0] = 0
        if (i > R) {
            // decrement count of pre[i - R - 1]
            s1.put(pre[i - R - 1], s1.get(pre[i - R - 1])-1);
            // if count is zero, element is not present
            // in map so remove it
            if (s1.get(pre[i - R - 1]) == 0)
                s1.remove(pre[i - R - 1]);
        }
 
        // insert pre[i - L]
        s1.put(pre[i - L], s1.getOrDefault(pre[i - L], 0)+1);
 
        // find minimum value in treemap.
        ans = Math.max(ans, pre[i] - s1.firstKey());
 
    }
    System.out.println(ans);
}
 
// Driver code
    public static void main(String[] args){
        int L, R;
        L = 1;
        R = 3;
        List<Integer> arr = Arrays.asList(1, 2, 2, 1);
        max_sum_subarray(arr, L, R);
    }
}
 
// This code is contributed by Utkarsh Sharma
 
 

C#




// C# program to find Maximum sum
// subarray of size between L and R.
using System;
using System.Collections.Generic;
class GFG
{
     
    // function to find Maximum sum subarray
    // of size between L and R
    static void max_sum_subarray(List<int> arr, int L, int R)
    {
        int n = arr.Count;
        int[] pre = new int[n];
       
        // calculating prefix sum
        pre[0] = arr[0];
        for (int i = 1; i < n; i++)
        {
            pre[i] = pre[i - 1] + arr[i];
        }
        List<int> s1 = new List<int>();
       
        // maintain 0 for initial
        // values of i upto R
        // Once i = R, then
        // we need to erase that 0 from
        // our multiset as our first
        // index of subarray
        // cannot be 0 anymore.
        s1.Add(0);
        int ans = Int32.MinValue;
       
        ans = Math.Max(ans, pre[L - 1]);
       
        // we maintain flag to
        // counter if that initial
        // 0 was erased from set or not.
        int flag = 0;
       
        for (int i = L; i < n; i++)
        {
       
            // erase 0 from multiset once i=b
            if (i - R >= 0)
            {
                if (flag == 0)
                {
       
                    int it = s1.IndexOf(0);
                    s1.RemoveAt(it);
                    flag = 1;
                }
            }
            // insert pre[i-L]
            if (i - L >= 0)
                s1.Add(pre[i - L]);
       
            // find minimum value in multiset.
            ans = Math.Max(ans, pre[i] - s1[0]);
       
            // erase pre[i-R]
            if (i - R >= 0)
            {
                int it = s1.IndexOf(pre[i - R]);
                s1.RemoveAt(it);
            }
        }
        Console.WriteLine(ans);
    } 
 
  // Driver code
  static void Main()
  {
    int L, R;
    L = 1;
    R = 3;
    List<int> arr = new List<int>(){1, 2, 2, 1};
    max_sum_subarray(arr, L, R);
  }
}
 
// This code is contributed by divyesh072019
 
 

Javascript




// Javascript program to find Maximum sum
// subarray of size between L and R.
 
// function to find Maximum sum subarray
  // of size between L and R
function max_sum_subarray(arr,L,R)
{
    let n = arr.length;
    let pre = new Array(n);
  
    // calculating prefix sum
    pre[0] = arr[0];
    for (let i = 1; i < n; i++)
    {
      pre[i] = pre[i - 1] + arr[i];
    }
    let s1 = []
  
    // maintain 0 for initial
    // values of i upto R
    // Once i = R, then
    // we need to erase that 0 from
    // our multiset as our first
    // index of subarray
    // cannot be 0 anymore.
    s1.push(0);
    let ans = Number.MIN_VALUE;
  
    ans = Math.max(ans, pre[L - 1]);
  
    // we maintain flag to
    // counter if that initial
    // 0 was erased from set or not.
    let flag = 0;
  
    for (let i = L; i < n; i++)
    {
  
      // erase 0 from multiset once i=b
      if (i - R >= 0)
      {
        if (flag == 0)
        {
          let it = s1.indexOf(0);
          s1.splice(it,1);
          flag = 1;
        }
      }
  
      // insert pre[i-L]
      if (i - L >= 0)
        s1.push(pre[i - L]);
  
      // find minimum value in multiset.
      ans = Math.max(ans, pre[i] - s1[0]);
  
      // erase pre[i-R]
      if (i - R >= 0)
      {
        let it = s1.indexOf(pre[i - R]);
        s1.splice(it,1);
      }
    }
    document.write(ans);
}
 
// Driver code
let L, R;
L = 1;
R = 3;
let arr = [1, 2, 2, 1];
max_sum_subarray(arr, L, R);
                 
// This code is contributed by avanitrachhadiya2155
 
 

Python3




def max_sum_subarray(arr, L, R):
    n = len(arr)
    pre = [0] * n
 
    # calculating prefix sum
    pre[0] = arr[0]
    for i in range(1, n):
        pre[i] = pre[i - 1] + arr[i]
 
    s1 = set()
 
    # maintain 0 for initial
    # values of i up to R
    # Once i = R, then
    # we need to erase that 0 from
    # our set as our first
    # index of subarray
    # cannot be 0 anymore.
    s1.add(0)
    ans = float('-inf')
 
    ans = max(ans, pre[L - 1])
 
    # we maintain flag to
    # counter if that initial
    # 0 was erased from set or not.
    flag = 0
 
    for i in range(L, n):
 
        # erase 0 from set once i=b
        if i - R >= 0:
            if flag == 0:
                s1.remove(0)
                flag = 1
 
        # insert pre[i-L]
        if i - L >= 0:
            s1.add(pre[i - L])
 
        # find minimum value in set.
        ans = max(ans, pre[i] - min(s1))
 
        # erase pre[i-R]
        if i - R >= 0:
            s1.remove(pre[i - R])
 
    print(ans)
 
# Driver code
if __name__ == "__main__":
    L, R = 1, 3
    arr = [1, 2, 2, 1]
    max_sum_subarray(arr, L, R)
 
 
Output
5 

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



Next Article
Maximum sum two non-overlapping subarrays of given size
author
yash2040
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Searching
  • prefix-sum
  • sliding-window
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Greedy
  • prefix-sum
  • Searching
  • sliding-window

Similar Reads

  • Size of The Subarray With Maximum Sum
    Given an array arr[] of size N, the task is to find the length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation : Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -
    10 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
  • 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
  • Find maximum (or minimum) sum of a subarray of size k
    Given an array of integers and a number k, find the maximum sum of a subarray of size k. Examples: Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39Explanation: We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Inp
    14 min read
  • Maximum of all subarrays of size K using Segment Tree
    Given an array arr[] and an integer K, the task is to find the maximum for each and every contiguous subarray of size K. Examples: Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 Output: 3 3 4 5 5 5 6 Explanation: Maximum of 1, 2, 3 is 3 Maximum of 2, 3, 1 is 3 Maximum of 3, 1, 4 is 4 Maximum of 1
    14 min read
  • Maximum subarray sum modulo m
    Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation. Examples: Input: arr[] = {10, 7, 18}, m = 13Output: 12Explanation: All subarrays and
    7 min read
  • Maximum of all Subarrays of size k using set in C++ STL
    Given an array of size N and an integer K, the task is to find the maximum for each and every contiguous sub-array of size K and print the sum of all these values in the end. Examples: Input: arr[] = {4, 10, 54, 11, 8, 7, 9}, K = 3 Output: 182 Input: arr[] = {1, 2, 3, 4, 1, 6, 7, 8, 2, 1}, K = 4 Out
    3 min read
  • CSES Solutions - Maximum Subarray Sum
    Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
    5 min read
  • Maximum sum subarray of size K with sum less than X
    Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, requ
    7 min read
  • Print subarray with maximum sum
    Given an array arr[], the task is to print the subarray having maximum sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}Output: {6, -2, -3, 1, 5}Explanation: The subarray {6, -2,
    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