something like this should solve your problem and handle all cases.
public static boolean canBeDividedEqually(int[] arr) {
if (arr.length % 2 != 0) {
return false;
}
int sum = getSum(arr);
if (sum % 2 != 0) {
return false;
}
return canBeDividedEqually(arr, sum);
}
public static int getSum(int[] arr) {
return getSum(arr, 0, 0);
}
private static int getSum(int[] arr, int sum, int index) {
if (index >= arr.length) {
return sum;
}
return getSum(arr, sum + arr[index], index + 1);
}
private static boolean canBeDividedEqually(int[] arr, int sum) {
// this can be optimized by canBeDividedEqually(arr, sum/2, arr[0], arr.length/2, 1, 1) because first element should always belong to first group, so we can start search from second element
return canBeDividedEqually(arr, sum/2, 0, arr.length/2, 0, 0);
// return canBeDividedEqually(arr, sum/2, arr[0], arr.length/2, 1, 1);
}
private static boolean canBeDividedEqually (int[] arr, int searchSum, int currentSum, int searchQuantity, int currentQuantity, int nextIndex) {
if(searchSum == currentSum && searchQuantity == currentQuantity) {
return true;
}
if(searchSum <= currentSum || searchQuantity <= currentQuantity) {
// we have too big sum or we take to much elements
return false;
}
if(nextIndex + (searchQuantity - currentQuantity) > arr.length) {
// we need to take more elements than we have still available
return false;
}
// add current element into account and search further
if(canBeDividedEqually(arr, searchSum, currentSum + arr[nextIndex], searchQuantity, currentQuantity + 1, nextIndex + 1)) {
System.out.println("true");
return true;
}
// if above "if" statement is not true, then skip current element and try to search further
return canBeDividedEqually(arr, searchSum, currentSum, searchQuantity, currentQuantity, nextIndex + 1);
}