Table of Contents
Methods to find the solution
Brute force method
Efficient method
Example
Output
Description of the above code
Subcount function
Conclusion
Home Backend Development C++ Write a program using C++ to find the number of subarrays with sum in a given range

Write a program using C++ to find the number of subarrays with sum in a given range

Sep 01, 2023 pm 02:37 PM
c programming subarray range and

Write a program using C++ to find the number of subarrays with sum in a given range

In this article, we will use a C program to find the number of sub-arrays whose sum is within a given range. We have an array of positive integers arr[] and a range {L, R} and we have to count the total number of subarrays whose sum falls within the given range L to R. So here is a simple example of the problem -

Input : arr[] = {1, 4, 6}, L = 3, R = 8

Output : 3

The subarrays are {1, 4}, {4}, {6}.


Input : arr[] = {2, 3, 5, 8}, L = 4, R = 13

Output : 6

The subarrays are {2, 3}, {2, 3, 5}, {3, 5},
{5}, {5, 8}, {8}.
Copy after login

Methods to find the solution

We will explain two ways to solve this problem using C#-

Brute force method

The most basic brute force approach is to calculate the sum of each subarray and then find whether that sum exists within a given range. (But this approach will take us a lot of time since its time complexity is O(n*n), where n is the size of the array).

Efficient method

Save Now, the efficient method is to use the sliding window technique, using this technique we will calculate the result faster or more efficiently in O(n).

Example

#include <bits/stdc++.h>
using namespace std;
int subCount(int *arr, int n, int x){
    int start = 0, end = 0, sum = 0, count = 0;
    while (end < n){ // we will be moving right border in this loop
        sum = sum + arr[end];
        while(start <= end && sum >= x){ // this loop will move our left border
            sum = sum - arr[start]; // we will decrement sum while moving left border.
                                   // For excluding the previous elements.
            start++;                // and move the left border.
        }
        count = count + ((end - start) + 1); // counting the subarrays.
        end++;
    }
    return count;
}
int main(){
    int arr[] = { 1, 4, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int L = 3;
    int R = 8;
    int answer;
    answer = subCount(arr, n, R)  - subCount(arr, n, (L - 1)); // Final Answer.
    cout << answer << "\n";
    return 0;
}
Copy after login

Output

3
Copy after login

Description of the above code

In this method, we count the number of subarrays whose sum is less than the upper limit of the given range , and then subtract the number of subarrays whose sum is less than the upper limit of the given range. Use the subcount function to get less than the lower limit of a given range.

Subcount function

This function uses the sliding window technique to find the count of a subarray with a count less than x.

First, we start with "end" and "start", Their values ​​are all 0. When we iterate over an array, we maintain the sum of the elements from beginning to end. After that, if our start is equal to end and the sum is greater than or equal to x, we start moving the start and keep decreasing the sum as we take elements out of the sum.

Until our sum becomes less than x or our start becomes greater than the end. Now we increase the count by the subarray count and then increase the right bound by 1. Now, after the outer loop ends, we return the total count of the subarray.

Conclusion

In this paper, we solved the problem of finding the number of subarrays whose sum is within a given range in O(n) time complexity using sliding window technique. We also learned about this problem from a C program and the complete way we can solve it easily (normally and efficiently). We can write the same program in other languages ​​like C, java, python etc.

The above is the detailed content of Write a program using C++ to find the number of subarrays with sum in a given range. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use C++ to write code to find the Nth non-square number Use C++ to write code to find the Nth non-square number Aug 30, 2023 pm 10:41 PM

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

Find the number of unique pairs in an array using C++ Find the number of unique pairs in an array using C++ Sep 07, 2023 am 11:53 AM

We need proper knowledge to create several unique pairs in array syntax of C++. While finding the number of unique pairs, we count all the unique pairs in the given array i.e. all possible pairs can be formed where each pair should be unique. For example -Input:array[]={5,5,9}Output:4Explanation:Thenumberoffalluniquepairsare(5,5),(5,9),(9,5)and(9,9).Input:array[]= {5,4,3,2,2}Output:16 Ways to Find Solution There are two ways to solve this problem, they are −

In C programming, find the area of ​​a circle In C programming, find the area of ​​a circle Aug 25, 2023 pm 10:57 PM

A circle is a closed figure. All points on a circle are equidistant from a point inside the circle. The center point is called the center of the circle. The distance from a point to the center of a circle is called the radius. Area is a quantitative representation of the span of dimensions of a closed figure. The area of ​​a circle is the area enclosed within the dimensions of the circle. The formula to calculate the area of ​​a circle, Area=π*r*r To calculate the area, we give the radius of the circle as input, we will use the formula to calculate the area, algorithm STEP1: Takeradiusasinputfromtheuserusingstdinput.STEP2: Calculatetheareaofcircleusing, area=(

Inversion algorithm for right rotation of array written in C++ Inversion algorithm for right rotation of array written in C++ Sep 08, 2023 pm 08:17 PM

In this article, we will learn about the reversal algorithm to rotate a given array to the right by k elements, for example −Input:arr[]={4,6,2,6,43,7,3,7},k= 4Output:{43,7,3,7,4,6,2,6}Explanation:Rotatingeachelementofarrayby4-elementtotherightgives{43,7,3,7,4,6,2,6}.Input:arr[]={8 ,5,8,2,1,4,9,3},k=3Output:{4,9,3,8,5,8,2,1} Find the solution

In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query Aug 29, 2023 am 11:21 AM

We have two arrays of integers, one with the calculated elements and the other with the split points required to split the array to generate subsets, we have to calculate the sum of each subset in each split and return the maximum subset Let's go through the example Understanding: - input −intarr[]=intarr[]={9,4,5,6,7}intsplitPoints[]={0,2,3,1}; output−the maximum subarray sum after each split [ 22,13,9,9] Explanation − Here we decompose the array according to its split points and get the maximum subset after each split and after the first split → {9} and {4,5,6,7 }>>The maximum sum of subarrays is -22 after the second split→{9},{4

Write a code using C++ to find the number of subarrays with the same minimum and maximum values Write a code using C++ to find the number of subarrays with the same minimum and maximum values Aug 25, 2023 pm 11:33 PM

In this article, we will use C++ to solve the problem of finding the number of subarrays whose maximum and minimum values ​​are the same. The following is an example of the problem −Input:array={2,3,6,6,2,4,4,4}Output:12Explanation:{2},{3},{6},{6},{2 },{4},{4},{4},{6,6},{4,4},{4,4}and{4,4,4}arethesubarrayswhichcanbeformedwithmaximumandminimumelementsame.Input:array={3,3, 1,5,

Reverse doubly linked list grouping by given size using C++ Reverse doubly linked list grouping by given size using C++ Sep 04, 2023 am 09:49 AM

In this problem, we are given a pointer to the head of the linked list and an integer k. In a group of size k, we need to reverse the linked list. For example -Input:1<->2<->3<->4<->5(doublylinkedlist),k=3Output:3<->2<->1<->5<->4 looking for solutions Method In this problem, we will formulate a recursive algorithm to solve this problem. In this method we will use recursion and solve the problem using recursion. Example#include<iostream&

Reversal algorithm for array rotation written in C++ Reversal algorithm for array rotation written in C++ Aug 28, 2023 pm 11:13 PM

In the given problem, we have an array and we need to rotate the array by d elements using inversion algorithm like −Input:arr[]=[1,2,3,4,5,6,7], d=2Output:arr[]=[3,4,5,6,7,1,2]Explanation:Asyoucanseewehavetorotatethisarraybyd=2butourmaintaskistoachievethisbyusingareversaltechnique. We performed some inversion technique calculations on the rotation of the array and concluded: First, we reverse

See all articles