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 Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count maximum non-overlapping subarrays with given sum
Next article icon

Maximize count of non-overlapping subarrays with sum K

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 10
Output: 3
Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2, 8}. Therefore, the required count is 3.

Input: arr[] = {1, 1, 1}, K = 2
Output: 1

Approach: The problem can be solved using the concept of prefix sum. Follow the below steps to solve the problem:

  1. Initialize a set to store all the prefix sums obtained up to the current element.
  2. Initialize variables prefixSum and res, to store the prefix sum of the current subarray and the count of subarrays with a sum equal to K respectively.
  3. Iterate over the array and for each array element, update prefixSum by adding to it the current element. Now, check if the value prefixSum – K is already present in the set or not. If found to be true, increment res, clear the set, and reset the value of prefixSum.
  4. Repeat the above steps until the entire array is traversed. Finally, print the value of res.

C++14




// C++ Program to implement
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to count the maximum
// number of subarrays with sum K
int CtSubarr(int arr[], int N, int K)
{
  
    // Stores all the distinct
    // prefixSums obtained
    unordered_set<int> st;
  
    // Stores the prefix sum
    // of the current subarray
    int prefixSum = 0;
  
    st.insert(prefixSum);
  
    // Stores the count of
    // subarrays with sum K
    int res = 0;
  
    for (int i = 0; i < N; i++) {
        prefixSum += arr[i];
  
        // If a subarray with sum K
        // is already found
        if (st.count(prefixSum - K)) {
  
            // Increase count
            res += 1;
  
            // Reset prefix sum
            prefixSum = 0;
  
            // Clear the set
            st.clear();
            st.insert(0);
        }
  
        // Insert the prefix sum
        st.insert(prefixSum);
    }
    return res;
}
  
// Driver Code
int main()
{
    int arr[] = { -2, 6, 6, 3, 5, 4, 1, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 10;
    cout << CtSubarr(arr, N, K);
}
 
 

Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG{
    // Function to count the maximum
    // number of subarrays with sum K
    static int CtSubarr(int[] arr, 
                        int N, int K)
    {
        // Stores all the distinct
        // prefixSums obtained
        Set<Integer> st = new HashSet<Integer>();
  
        // Stores the prefix sum
        // of the current subarray
        int prefixSum = 0;
  
        st.add(prefixSum);
  
        // Stores the count of
        // subarrays with sum K
        int res = 0;
  
        for (int i = 0; i < N; i++) 
        {
            prefixSum += arr[i];
  
            // If a subarray with sum K
            // is already found
            if (st.contains(prefixSum - K)) 
            {
                // Increase count
                res += 1;
  
                // Reset prefix sum
                prefixSum = 0;
  
                // Clear the set
                st.clear();
                st.add(0);
            }
  
            // Insert the prefix sum
            st.add(prefixSum);
        }
        return res;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = {-2, 6, 6, 3, 
                     5, 4, 1, 2, 8};
        int N = arr.length;
        int K = 10;
        System.out.println(CtSubarr(arr, N, K));
    }
}
  
// This code is contributed by Chitranayal
 
 

Python3




# Python3 program to implement
# the above approach
  
# Function to count the maximum 
# number of subarrays with sum K
def CtSubarr(arr, N, K):
  
    # Stores all the distinct
    # prefixSums obtained
    st = set()
  
    # Stores the prefix sum
    # of the current subarray
    prefixSum = 0
  
    st.add(prefixSum)
  
    # Stores the count of
    # subarrays with sum K
    res = 0
  
    for i in range(N):
        prefixSum += arr[i]
  
        # If a subarray with sum K
        # is already found
        if((prefixSum - K) in st):
  
            # Increase count
            res += 1
  
            # Reset prefix sum
            prefixSum = 0
  
            # Clear the set
            st.clear()
            st.add(0)
  
        # Insert the prefix sum
        st.add(prefixSum)
  
    return res
  
# Driver Code
arr = [ -2, 6, 6, 3, 5, 4, 1, 2, 8 ]
N = len(arr)
K = 10
  
# Function call
print(CtSubarr(arr, N, K))
  
# This code is contributed by Shivam Singh
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
      
// Function to count the maximum
// number of subarrays with sum K
static int CtSubarr(int[] arr, 
                    int N, int K)
{
      
    // Stores all the distinct
    // prefixSums obtained
    HashSet<int> st = new HashSet<int>();
  
    // Stores the prefix sum
    // of the current subarray
    int prefixSum = 0;
  
    st.Add(prefixSum);
  
    // Stores the count of
    // subarrays with sum K
    int res = 0;
  
    for(int i = 0; i < N; i++) 
    {
        prefixSum += arr[i];
  
        // If a subarray with sum K
        // is already found
        if (st.Contains(prefixSum - K)) 
        {
              
            // Increase count
            res += 1;
  
            // Reset prefix sum
            prefixSum = 0;
  
            // Clear the set
            st.Clear();
            st.Add(0);
        }
  
        // Insert the prefix sum
        st.Add(prefixSum);
    }
    return res;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { -2, 6, 6, 3, 
                   5, 4, 1, 2, 8};
    int N = arr.Length;
    int K = 10;
      
    Console.WriteLine(CtSubarr(arr, N, K));
}
}
  
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
  
// Javascript Program to implement
// the above approach
  
// Function to count the maximum
// number of subarrays with sum K
function CtSubarr(arr, N, K)
{
  
    // Stores all the distinct
    // prefixSums obtained
    var st = new Set();
  
    // Stores the prefix sum
    // of the current subarray
    var prefixSum = 0;
  
    st.add(prefixSum);
  
    // Stores the count of
    // subarrays with sum K
    var res = 0;
  
    for (var i = 0; i < N; i++) {
        prefixSum += arr[i];
  
        // If a subarray with sum K
        // is already found
        if (st.has(prefixSum - K)) {
  
            // Increase count
            res += 1;
  
            // Reset prefix sum
            prefixSum = 0;
  
            // Clear the set
            st = new Set();
            st.add(0);
        }
  
        // Insert the prefix sum
        st.add(prefixSum);
    }
    return res;
}
  
// Driver Code
var arr = [-2, 6, 6, 3, 5, 4, 1, 2, 8];
var N = arr.length;
var K = 10;
document.write( CtSubarr(arr, N, K));
  
// This code is contributed by importantly.
</script>
 
 
Output: 
3

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Count maximum non-overlapping subarrays with given sum
author
offbeat
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • Searching
  • Amazon
  • cpp-set
  • prefix-sum
  • subarray
Practice Tags :
  • Amazon
  • Arrays
  • Hash
  • Mathematical
  • prefix-sum
  • Searching

Similar Reads

  • 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 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
  • 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
  • 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 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
  • 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
  • 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
  • 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
  • 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
  • Count of subarrays with maximum value as K
    Given an array arr[] of N integers and an integer K. The task is to find the number of subarrays with a maximum value is equal to K. Examples: Input: arr[ ] = {2, 1, 3, 4}, K = 3Output: 3Explanation: Sub-arrays with maximum value is equals K are { 2, 1, 3 }, { 1, 3 }, { 3 }, hence the answer is 3. I
    8 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