遞歸實現(JAVA):
private static long minimalDiff(int[] nums, int sumA, int sumB, int indexA, int indexB) {
int index = indexA + indexB + 2;
if (index == nums.length) {
return Math.abs(sumA - sumB);
} else if (Math.max(indexA, indexB) * 2 > nums.length - 1) {
return Integer.MAX_VALUE;
} else if (Math.abs(sumA + nums[index] - sumB) < Math.abs(sumB + nums[index] - sumA)){
long result = minimalDiff(nums, sumA + nums[index], sumB, indexA + 1, indexB);
if (result > 0) {
result = Math.min(result, minimalDiff(nums, sumB + nums[index], sumA, indexB + 1, indexA));
}
return result;
} else {
long result = minimalDiff(nums, sumB + nums[index], sumA, indexB + 1, indexA);
if (result > 0) {
result = Math.min(result, minimalDiff(nums, sumA + nums[index], sumB, indexA + 1, indexB));
}
return result;
}
}
public static long minimalDiff(int[] num) {
if (num == null || num.length < 2){
throw new IllegalArgumentException("num");
}
return minimalDiff(num, 0, 0, -1, -1);
}
public static void main(String[] args) {
int [] test= {4, 5, 3, 55, -3, 23, 3, 20, 100, 90};
System.out.println("Answer: "+minimalDiff(test));
}
它打印:
Answer: 0
請提供原始問題的鏈接。 – MrSmith42
@ MrSmith42我已經在問題中提供了鏈接。 – Utkarsh