×

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java.

To solve this problem, we will check for numbers if they lie in between or the range lies in between I and R then we have to increase the count.

The procedure or algorithm is as follows:

  • Set the variables count and temp to zero.
  • iterate I from 0 to the array's size minus 1. This would determine where our subarrays would begin.
  • Update temp=0, each time the loop runs.
  • Repeat steps j from i until array-1's size. This would determine where our subarrays will terminate.
  • The temporary variable as temp+=Nums[j];
  • Increase count by 1 if temp>=L or temp=R.
  • Return rate.

Example code:

import java.util.*;
import java.io.*;
public class TestRangeSum 
{  
 
    public int countrange(int arr[], int n, int l, int r)  
{  
    long temp = 0;  
    int count = 0;  
    for (int j = 0; j < n; j++)  
    {  
        temp = 0;  
        for (int i = j; i < n; i++)  
        {  
            //The ith index varies with each iteration, which causes the size of the sub-array to vary as well. As a result, the total also changes with each iteration, and these changes are reflected or stored in the temp variable.  
            temp = temp + arr[i];  
  
            // Increase the count by one if the amount is inside the range. 
            if(temp >= l && temp <= r)  
            {  
                count = count + 1;  
            }  
        }  
    }  
return count;  
}  
public static void main(String args[])  
{  
    TestRangeSum  obj = new TestRangeSum();  
    int arr[] = {11, 12, 13, 14, 15, 16, 17};  
    int n = arr.length;  
    int l = 12;  
    int r = 17;  
    int answer = obj.countrange(arr, n, l, r);  
    System.out.println("the initial array: ");  
    for(int i = 0; i < n; i++)  
    {  
        System.out.print(arr[i] + " ");      
    }  
    System.out.println();  
    if(answer != 0)  
    {  
        System.out.print("The sum lies in range between "+ l + " & " + r + " is " + answer + ".");  
    }  
    else  
    {  
        System.out.print("There is no range whose sum lies between "+ l + " & " + r + ".");      
    }  
  
    System.out.println("\n");  
    int arr1[] = {111, 112, 113, 114, 115, 116, 117};  
  
    // the size 
    n = arr1.length;  
    l = 19;  
    r = 110;  
    answer = obj.countrange(arr1, n, l, r);  
    System.out.println("For initial array: ");  
    for(int i = 0; i < n; i++)  
    {  
        System.out.print(arr1[i] + " ");      
    }  
    System.out.println();  
    if(answer != 0)  
    {  
        System.out.print("The range in between between "+ l + " & " + r + " is " + answer + ".");  
    }  
    else  
    {  
        System.out.print("There is no range whose sum lies between "+ l + " & " + r + ".");      
    }  
}  
  
}  

Output:

the initial array: 
11 12 13 14 15 16 17 
The sum lies in range between 12 & 17 is 6.


For initial array: 
111 112 113 114 115 116 117 
There is no range whose sum lies between 19 & 110.

To calculate the solution, we used nested for-loops. As a result, the program's time complexity is O(n2), where n is the total number of elements in the array. Additionally, we didn't employ a data structure to store the findings. As a result, the program's space complexity, which is O, is constant (1).

Another approach:

With this strategy, we'll strive to make the program's time complexity go from O (n2). In this approach, we merge the answers while counting the answers using merge sort. The left half [start, mid] and right half [mid, end] have previously been sorted at the merge stage. Then, using index I we iterate through the left half. It is necessary to calculate the two indices m and n in the right half for each I, where n is the first index that satisfies the condition sumArr[n] - sumArr[i] = right and k is the first index that satisfies the condition sumArr[m] - sumArr[i] left. So, n - m is the total number of sums in [left, right].

Process:

In this merge-sort approach, we count the response as we combine. The left half [start, mid] and right half [mid, end] have previously been sorted at the merge stage.

Then, using index I we iterate through the left half. To discover two indices k and j that satisfy sums[j] - sums[i] > R and k that satisfy sums[k] - sums[i] >= L for each I we must search the right half.

There is then j - k sums in [L, R].

Algorithm:

Step 1: A function for merging subarray counts; int mcount (int [] sum, int L, int R, int start, int end)

Step 2: First, handle the extreme situations; if end-start > 0, then return 0.

Step 3: Initialize the variable mid with the formula: mid = (start + end)/2, m = n, and mid.

Step 4: Create a variable called count, and then update it as follows: count=mcout(sum,L,R,start,mid) + mcount (sum,L,R,mid,end)

Step 5: Repeat step 1 from 0 to mid.

  • As long as (m<end and sum[m]-sum[i]L) m++
  • as long as (n<end and sum[n]-sum[i]=R) n++
  • as count+=n-m, update the count.

Step 6: Return the count.

Step 7: CountRangeSum is a function that counts the number of sum ranges (int [] nums, int L, int R).

  • Create an array of long ints with a length equal to nums+1 in order to prevent int overflows.
  • Update sum as sum[i+1]=sum[i]+nums[i] as you iterate I from 0 to n.
  • The value acquired by the previous function mcount(sum,L,R,0,n+1) is then returned.
// important import packages
import java.util.*;
import java.io.*;
import java.util.Arrays;  
public class RangeSum  
{  
    static int mergeSum(int arr[], int l, int r, int start, int end)  
    {  
    // base conditions 
        if (end - start <= 1)  
        {  
            return 0;  
        }  
        int mid = (start + end) / 2;  
        int a = mid;  
        int b = mid;  
        int count = mergeSum(arr, l, r, start, mid) + mergeSum(arr, l, r, mid, end);  
        // counting valid ranges 
        for (int j = start; j < mid; j++)  
        {  
            while (a < end && arr[a] - arr[j] < l)  
            {  
                a = a + 1;  
            }      
            while (b < end && arr[b] - arr[j] <= r)  
            {  
                b = b + 1;  
            }  
            count = count + b - a;  
        }   
        //combining the two sorted sections, then copying the sorted outcome back to the array arr[] 
        Arrays.sort(arr, start, end);  
        return count;  
    }  
    public static int findRangeSum(int narr[], int n, int l, int r)  
    {  
    int arr[] = new int[n + 1];      
    // initializing of the elements in the arr[] to 0  
    for (int i = 0; i < n + 1; i++)  
    {  
        arr[i] = 0;   
    }  
    // a computational loop the initial sum
    //It is done so that we can rapidly calculate the range sum. 
    for (int j = 0; j < n; j++)  
    {  
         arr[j + 1] = arr[j] + narr[j];  
    }  
    return mergeSum(arr, l, r, 0, n + 1);  
    }  
      
    // main method  
    public static void main(String argvs[])  
    {  
    // creating an object of the class RangeSum
    RangeSum obj = new RangeSum();  
      
    // input array  
    int narr[] = {10, 20, 30, 40, 50, 60, 70};  
      
    // size declaration  
    int n = narr.length;  
      
    // defining the boundaries i.e, the l and the r ranges  
    int l = 20;  
    int r = 70; 
    int ans = obj.findRangeSum(narr, n, l, r);  
      
    System.out.println("For the input array: ");  
      
    for(int i = 0; i < n; i++)  
    {  
    System.out.print(narr[i] + " ");      
    }  
    System.out.println();  
      
    if(ans != 0)  
    {  
    System.out.print("The number of ranges whose sum lies between "+ l + " & " + r + " is " + ans + ".");  
    }  
    else  
    {  
    System.out.print("There is no range whose sum lies between "+ l+ " & " + r + ".");      
    }  
      
    System.out.println("\n");  
      
    // input array  
    int narr1[] = {11, 12, 13, 14, 15, 16, 17};  
      
    // computing its size  
    n = narr1.length;  
      
    // defining the ranges, i.e, the left and the right boundary   
    l = 9;  
    r = 10;  
      
    // invoking the method findCountRangeSum() and storing the answer  
    ans = obj.findRangeSum(narr1, n, l, r);  
      
    System.out.println("input array: ");  
      
    for(int i = 0; i < n; i++)  
    {  
        System.out.print(narr1[i] + " ");      
    }  
    System.out.println();  
      
    if(ans != 0)  
    {  
    System.out.print("The range in between the sum lies is "+ l + " & " + r + " is " + ans + ".");  
    }  
    else  
    {  
    System.out.print("The range in between the sum does not lies is "+ l + " & " + r+ ".");      
    }  
    }  
      
    }  

Output:

For the input array: 10 20 30 40 50 60 70 
The number of ranges whose sum lies between 20 & 70 is 10.


input array: 
11 12 13 14 15 16 17 
The range in between the sum does not lies is 9 & 10.

Related Topics

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.