Hello coders, In this post, you will learn how to solve Java Subarray Hacker Rank Solution. This problem is a part of the Java programming series.
One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

Java Subarray Hacker Rank Solution
Problem
We define the following:
- A subarray of an -element array is an array composed from a contiguous block of the original array’s elements. For example, if , then the subarrays are , , , , , and . Something like would not be a subarray as it’s not a contiguous subsection of the original array.
- The sum of an array is the total sum of its elements.
- An array’s sum is negative if the total sum of its elements is negative.
- An array’s sum is positive if the total sum of its elements is positive.
Given an array of integers, find and print its number of negative subarrays on a new line.
Problem Statement; Click Here.
Java Subarray Hacker Rank Solution
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int length = sc.nextInt(); int[] arr = new int[length]; int first = sc.nextInt(); arr[0] = first; int count = first < 0 ? 1 : 0; for (int i = 1; i < length; i++){ int num = sc.nextInt(); arr[i] = arr[i - 1] + num; if (arr[i] < 0){ count++; } for (int j = 0; j < i; j++){ int sub_result = arr[i] - arr[j]; if (sub_result < 0){ count++; } } } System.out.print(count); } }
Disclaimer: The above Problem (Java Subarray) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.