Print the number of subarrays of an array having negative sums with Java HackerRank solutions.
Task
Given an array of n integers, find and print its number of negative subarrays on a new line.
Input Format
The first line contains a single integer, n, denoting the length of array A = [a0, a1,...,an-1].
The second line contains n space-separated integers describing each respective element, ai, in array A.
Output Format
Print the number of subarrays of A having negative sums.
Sample Input
5
1 -2 4 -5 1
Sample Output
9
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 n = sc.nextInt();
int[] A = new int[n];
for(int i=0;i<A.length;i++)
{
A[i] = sc.nextInt();
}
int count = 0, sum;
for(int i=0;i<A.length;i++)
{
sum = 0;
for(int j=i;j<A.length;j++)
{
sum = A[j] + sum;
if(sum<0)
{
count++;
}
}
}
System.out.println(count);
}
}
Steps involved in this solution:
1. Import necessary packages.
2. Define a class named Solution, which will contain the main method.
3. Define the main method, the entry point of the program.
4. Create a Scanner object named sc to read input from the user.
5. Read an integer n, representing the size of the array.
6. Create an array A
of size n. Use a loop to read n integers from the user and store them in the array.
7. Initialize a variable count to 0, to keep track of subarrays with negative sums. Use two loops to generate all subarrays and calculate their sum. If the sum of a subarray is negative, increment the count.
8. Print the count of subarrays with negative sums.
9. Close the Scanner to release resources. Close the class definition.