Java Subarray – Hacker Rank Solution

Java Subarray - Hacker Rank Solution
Java Subarray- Hacker Rank Solution

Problem :

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- Hacker Rank Solution

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 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.

Leave a Comment