1
\$\begingroup\$

Given an array of N integers, find and print its number of negative subarrays (i.e sub arrays having negative summation) on a new line.

My code is taking \$\mathcal{O}(n^2)\$ time. How can I improve this?

import java.util.Scanner;
public class Solution {
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 int numberOfInts = sc.nextInt();
 int[] arr = new int[numberOfInts];
 for (int i = 0; i < numberOfInts; i++) {
 arr[i] = sc.nextInt();
 }
 int count = 0;
 for (int i = 0; i < numberOfInts - 2; i++) {
 int sum = arr[i];
 if (arr[i] < 0) {
 count++;
 }
 for (int j = i + 1; j < numberOfInts; j++) {
 sum = sum + arr[j];
 if (sum < 0) {
 count++;
 }
 }
 }
 if (arr[numberOfInts - 1] < 0) {
 count++;
 }
 System.out.println(count);
 }
}
Graipher
41.6k7 gold badges70 silver badges134 bronze badges
asked Oct 6, 2017 at 1:31
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Your code doesn't work for an empty array. Therefore it is conceptually wrong.

You should rewrite your code to be easily and automatically testable. This means to extract the interesting part of the program and separate it from the rest. In this case, the interesting part is the given an array, find. The code should therefore look like this:

static int countNegativeSubarrays(int... numbers) {
 int count = 0;
 // Your code here
 return count;
}

This method can be called easily from a test method:

static void runSelfTest() {
 if (countNegativeSubarrays() != 0)
 throw new AssertionError();
 if (countNegativeSubarrays(-1) != 1)
 throw new AssertionError();
 if (countNegativeSubarrays(-1, -1) != 3)
 throw new AssertionError();
 if (countNegativeSubarrays(-1, -1, -1) != 6)
 throw new AssertionError();
 if (countNegativeSubarrays(1, -1, -2, 5) != 4)
 throw new AssertionError();
 // Add more test cases here
}

In your main method you should run this self-test before accepting any input from the user.

answered Oct 6, 2017 at 6:08
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.