-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubArray.java
More file actions
47 lines (32 loc) · 985 Bytes
/
Copy pathSubArray.java
File metadata and controls
47 lines (32 loc) · 985 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*Given an array of integers, count how many subarrays have a negative sum.
A subarray is a contiguous part of the array.*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read array size
int n = sc.nextInt();
// Create array
int[] a = new int[n];
// Store array elements
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int count = 0;
// Generate all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
// Add current element to subarray sum
sum += a[j];
// Count negative subarrays
if (sum < 0) {
count++;
}
}
}
// Print answer
System.out.println(count);
sc.close();
}
}