The Wayback Machine - https://web.archive.org/web/20211208103109/https://www.geeksforgeeks.org/count-of-subarrays-with-unique-sum-with-sum-at-most-k/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of subarrays with unique sum with sum at most K

  • Last Updated : 08 Dec, 2021

Given an array arr[] of size N and an integer K., The task is to count the number of subarrays with unique sum with sum at most K.

Examples:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: N = 3, arr[] = {1, 0, 1}, K = 1
Output: 3
Explanation: All Subarrays are [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] & The sum of these subarrays are {1, 0, 1, 1, 1, 2} respectively. There are only 2 distinct possible sums less than or equal to 1
Input: N = 1, arr[] = {1}, K = 0
Output: 0



 

Approach: The task can be solved by calculating sums of each subarray and storing them in a HashMap. Iterate over the HashMap, and increment the count, if the sum is at most K

Below is the implementation of the above approach

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate the valid sums
void solve(int arr[], int n, int k)
{
  
    // Store the distinct subarray sums
    unordered_map<int, int> occ;
  
    int cur = 0;
    for (int i = 0; i < n; i++) {
        cur = 0;
        for (int j = i; j < n; j++) {
            cur += arr[j];
            occ[cur]++;
        }
    }
  
    // Stores the answer
    int ans = 0;
    for (auto x : occ) {
        if (x.first <= k)
            ans++;
    }
  
    cout << ans << endl;
}
  
// Driver Code
int main()
{
    int N = 3, K = 1;
    int arr[3] = { 1, 0, 1 };
  
    solve(arr, N, K);
    return 0;
}
Output
2

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!