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

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

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 BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Java Arraylist HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad