Files
HackerRank-Solutions/Java/Data Structures/Java Subarray/Solution.java
T

40 lines
1.1 KiB
Java
Raw Normal View History

2017-02-16 23:51:56 -06:00
// Author: Rodney Shaghoulian
// Github: github.com/rshaghoulian
// HackerRank: hackerrank.com/rshaghoulian
import java.util.Scanner;
2017-04-05 18:42:35 -05:00
// Our subarray must be contiguous, so we have O(n^2) contiguous subarrays
2017-02-16 23:51:56 -06:00
2017-04-05 18:42:35 -05:00
// Time Complexity: O(n^2)
// Space Complexity: O(1)
public class Solution {
2017-02-16 23:51:56 -06:00
public static void main(String[] args) {
2017-04-05 18:42:35 -05:00
/* Save input */
2017-02-16 23:51:56 -06:00
Scanner scan = new Scanner(System.in);
2017-04-05 18:42:35 -05:00
int size = scan.nextInt();
2017-02-16 23:51:56 -06:00
int [] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scan.nextInt();
}
scan.close();
System.out.println(negativeSubarrays(array));
}
private static int negativeSubarrays(int [] array) {
int count = 0;
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i; j < array.length; j++) {
sum += array[j];
if (sum < 0) {
count++;
}
}
sum = 0;
}
return count;
}
}