Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Find the total number of continuous subarrays in a specified array of integers

Java Basic: Exercise-202 with Solution

Write a Java program to find the total number of continuous subarrays in a given array of integers whose sum equals to an given integer.

Example:
Original Array: [4, 2, 3, 3, 7, 2, 4]
Value of k: 6 Total number of continuous subarrays: 3

Pictorial Presentation:

Java Basic Exercises: Find the total number of continuous subarrays in a specified array of integers

Sample Solution:

Java Code:

import java.util.*;
public class Solution {
    public static void main(String[] args) {		
        int[] nums = {4,2,3,3,7,2,4};
		int k = 6;
		System.out.print("Original Array: "+Arrays.toString(nums));
		System.out.print("\nValue of k: "+k);
		System.out.print("\nTotal number of continuous subarrays: "+max_SubArray(nums, k));       
    }     
   public static int max_SubArray(int[] nums, int k) {
   int ctr = 0, sum = 0;
        Map<Integer, Integer>map = new HashMap<>();
        
        map.put(0, 1);
        
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            
            if (map.containsKey(sum - k)) {
                ctr = ctr + map.get(sum - k);
            }
            
            if (map.containsKey(sum)) {
                map.put(sum, map.get(sum) + 1);
            } else {
                map.put(sum, 1);
            }
        }
        
        return ctr;
    }
}


Sample Output:

Original Array: [4, 2, 3, 3, 7, 2, 4]
Value of k: 6
Total number of continuous subarrays: 3

Flowchart:

Flowchart: Java exercises: Find the total number of continuous subarrays in a specified array of integers

Java Code Editor:

Company:  Google

Contribute your code and comments through Disqus.

Previous: Write a Java program to divide a given array of integers into given k non-empty subsets whose sums are all equal. Return true if all sums are equal otherwise return false.
Next: Write a Java program to find the contiguous subarray of given length k which has the maximum average value of a given array of integers. Display the maximum average value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe