Java Hacker rank SubArray

 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.

Input Format

The first line contains a single integer, , denoting the length of array .
The second line contains  space-separated integers describing each respective element, , in array .

Constraints

Output Format

Print the number of subarrays of  having negative sums.

Sample Input

5
1 -2 4 -5 1

Sample Output

9

Explanation

There are nine negative subarrays of :

Thus, we print  on a new line.

Solution 


import java.io.*;
import java.util.*;

public class SubArray {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] ary = new int[num];
for (int i = 0; i< num; i++){
ary[i] = sc.nextInt();
}

int count = 0;
for (int j = 0;j< num;j++){
for (int k = 0; k < num; k++) {
if(j<=k) {
int[] tempArray = Arrays.copyOfRange(ary, j, k+1);
int sum = getSumOfArrayElements(tempArray);
if (sum < 0) {
count++;
}
}
}
}

System.out.println(count);

}

private static int getSumOfArrayElements(int[] tempArray) {
int sum = 0;
for (int i = 0; i < tempArray.length; i++) {
sum += tempArray[i];
}
return sum;
}
}



Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting

Hackerrank - Day of the Programmer

Hackerrank - UNIQUE ARMSTRONG NUMBER