Java Subarray Hackerrank Problem coderinme

Java Subarray

A subarray of an n-element array is an array composed from a contiguous block of the original array’s elements. For example, if array=[1,2,3], then the subarrays are [1],[2],[3],[1,2],[2,3] and [1,2,3]. Something like [1,3] 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, n, denoting the length of array A=[a0,a1,a2,…an-1].
The second line contains space-separated integers describing each respective element, , in array .

Constraints
1<=n<=100
-10000<=ai<=10000
Output Format

Print the number of subarrays of A having negative sums.

Sample Input

5
1 -2 4 -5 1
Sample Output

9
Explanation

Java Subarray

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        
        for(int i = 0;i < n;i++){
            a[i] = scan.nextInt();
        }
        scan.close();
        
        int numNegativeSubarrays = 0;
        
        for(int i = 0; i < n; i++) {
            for(int j = i; j < n; j++) {
                
                int sum = 0;
                
                for(int k = i; k <= j; k++) {
                    sum = sum + a[k];
                }
                
                if(sum < 0) {
                    numNegativeSubarrays++;
                }
            }
        }
        
        System.out.println(numNegativeSubarrays);
    }
}

Java Subarray

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

2 comments: On Java Subarray Hackerrank Problem coderinme

Leave a reply:

Your email address will not be published.