Java Subarray HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java Subarray HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Java Subarray HackerRank Solution
Java Subarray HackerRank Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java Subarray HackerRank Solutions


We define the following:

  • 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 HackerRank Solutions

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(;
    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){
        for (int j = 0; j < i; j++){
            int sub_result = arr[i] - arr[j];
            if (sub_result < 0){

Disclaimer: The above Problem (Java Subarray) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Java Arraylist HackerRank Solution

Leave a Reply

Your email address will not be published. Required fields are marked *