I think an algorithm could be to pick the pair based on the largest and second- (or joint-) largest element.
// Assuming in.length > 1.
Arrays.sort(in);
while (in[in.length - 1] != 0 && in[in.length - 2] != 0) {
// Decrement the elements.
--in[in.length-1];
--in[in.length-2];
// Restore the sorted order
// (could do this by bubbling the changed elements, done with sort for clarity)
Arrays.sort(in);
}
if (in[in.length - 1] == 0) {
System.out.println("Is a zero array");
} else {
System.out.println("Not a zero array");
}
Trying with the inputs in the question Ideone:
[1, 2, 1, 1] is not a zero array
[1, 2, 3, 4] is a zero array
[1, 1, 2, 2] is a zero array
And another:
[1, 1, 2] is a zero array (112 -> 011 -> 000)
Actually, full sorting isn't necessary, since you're only interested in the values in the last 2 positions in the array.
void zero(int[] in) {
if (in.length > 1) {
restore(in);
while (in[in.length - 1] != 0 && in[in.length - 2] != 0) {
--in[in.length-1];
--in[in.length-2];
restore(in);
}
}
if (in.length == 0 || in[in.length - 1] == 0) {
System.out.println("Is a zero array");
} else {
System.out.println("Not a zero array");
}
}
void restore(int[] in) {
// Find the largest element in the array, swap with the last element.
int largest = largestIndex(in, 0, in.length);
swap(in, largest, in.length-1);
// Find the largest element in the array, excluding last element, swap with the second-last element.
int second = largestIndex(in, 0, in.length-1);
swap(in, second, in.length-2);
}
void swap(int[] in, int i, int j) {
int tmp = in[i];
in[i] = in[j];
in[j] = tmp;
}
int largestIndex(int[] in, int from, int to) {
int result = from;
for (int i = from + 1; i < to; ++i) {
if (in[i] > in[result]) result = i;
}
return result;
}