I’m doing Sleeping In Class, but my code only works for some of the cases.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Main1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int t = reader.nextInt();
int[] answers = new int[t];
for (int i = 0; i < t; i++) {
answers[i] = solve();
}
for (int j = 0; j < t; j++) {
System.out.println(answers[j]);
}
}
static int solve() {
int n = reader.nextInt();
int[] nums = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
nums[i] = reader.nextInt();
sum += nums[i];
}
ArrayList<Integer> modificationsList = new ArrayList<Integer>();
if (sum == 0) {
return 0;
} else {
for (int j = 1; j <= Math.sqrt(sum); j++) {
if (sum % j == 0) {
int modifications = findModifications(sum / j, nums);
if (modifications >= 0) {
modificationsList.add(modifications);
}
}
}
}
return Collections.min(modificationsList);
}
static int findModifications(int num, int[] nums) {
int modifications = 0;
int sum = nums[0];
int k = 1;
while (k < nums.length) {
if (sum == num) {
if (k == nums.length - 1) {
break;
} else {
sum = nums[k];
k++;
}
} else if (sum > num) {
modifications = -1;
break;
} else {
sum += nums[k];
modifications++;
k++;
}
}
return modifications;
}
}
I’m pretty sure the problem is in the function that finds the number of modifications, but I can’t tell how it goes wrong for certain inputs.