HackerRank Java- Subarray




Given an array of n integers, find and print its number of negative subarrays on a new line.



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Solution {
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9. int n = sc.nextInt();
  10. int[] a = new int[n];
  11. for (int i = 0; i < n; i++) {
  12. a[i] = sc.nextInt();
  13. }
  14. sc.close();
  15. int negativeSubarrays = 0;
  16. for (int i = 0; i < n; i++) {
  17. int sum = 0;
  18. for (int j = i; j < n; j++) {
  19. sum += a[j];
  20. if (sum < 0) {
  21. negativeSubarrays++;
  22. }
  23. }
  24. }
  25. System.out.println(negativeSubarrays);
  26. }
  27. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube