Search code examples
javasub-array

How do I print the number of negative subarrays from a given array?


Problem Statement:

Given an array of n integers, find and print its number of negative subarrays on a new line.(A subarray is negative if the total sum of its elements is negative.)

Sample Input

5

1 -2 4 -5 1

Sample Output

9

Result that my code yields

Input (stdin)

5

1 -2 4 -5 1

Your Output (stdout)

7

Expected Output

9

Compiler Message

Wrong Answer

My code:

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 scan = new Scanner(System.in);
        int n = scan.nextInt();
        int a[] = new int[n];
        int b[] = new int[n];
        int count=0;
        int i,j,sum = 0;
        for(i=0;i<n;i++)
            {
            a[i] = scan.nextInt();            
        }
        for(i=0;i<n;i++)
            {
        if(a[i]<0){count++;}
        }
        for(i=0;i<n;i++)
            {
            for(j=0;j<n;j++)
                {
            sum = a[i] + sum;
            b[j] = sum;
            }
        }
        for(j=0;j<n;j++)
                {
        if(b[j]<0){count++;}
        }
        System.out.println(count);
        
    } 
}

Where am I going wrong ?


Solution

  • Made few changes to the previous logic and now this code works fine.

    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];
                int count=0;
                int i,j,sum = 0;
                for(i=0;i<n;i++)
                {
                    a[i] = scan.nextInt();
                }
                scan.close();
                for(i=0;i<n;i++)
                {
                    sum = 0;
                    for(j=i;j<n;j++)
                    {
                        sum = a[j] + sum;
                        if(sum<0){
                            count++;
                        }
                    }
                }
                System.out.println(count);
            }
        }