-
Notifications
You must be signed in to change notification settings - Fork 14
/
Balanced_array.java
50 lines (39 loc) · 1.35 KB
/
Balanced_array.java
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
48
49
50
import java.util.Scanner;
public class BalancedArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the size of the array
int n = scanner.nextInt();
// Initialize the array and read its elements
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
// Call the method to count balanced splits
int result = countBalancedSplits(a, n);
// Print the result
System.out.println(result);
scanner.close();
}
private static int countBalancedSplits(int[] a, int n) {
int totalCount = 0;
// Iterate through possible split points
for (int i = 1; i < n; i++) {
// Calculate sum of the first part
int leftSum = 0;
for (int j = 0; j < i; j++) {
leftSum += a[j];
}
// Calculate sum of the second part
int rightSum = 0;
for (int j = i; j < n; j++) {
rightSum += a[j];
}
// Check if the two parts are balanced
if (leftSum == rightSum) {
totalCount++;
}
}
return totalCount;
}
}