fork download
  1. import java.util.*;
  2.  
  3. /* Name of the class has to be "Main" only if the class is public. */
  4. class Ideone {
  5. static void zero(int[] in) {
  6. int[] original = Arrays.copyOf(in, in.length);
  7.  
  8. if (in.length > 1) {
  9. Arrays.sort(in);
  10. while (in[in.length - 1] != 0 && in[in.length - 2] != 0) {
  11. // Decrement the elements.
  12. --in[in.length - 1];
  13. --in[in.length - 2];
  14.  
  15. // Restore the sorted order
  16. // (could do this by bubbling the changed elements, done with sort for clarity)
  17. Arrays.sort(in);
  18. }
  19. }
  20.  
  21. System.out.print(Arrays.toString(original));
  22. if (in[in.length - 1] == 0) {
  23. System.out.println(" is a zero array");
  24. } else {
  25. System.out.println(" is not a zero array");
  26. }
  27. }
  28.  
  29. public static void main(String[] args) throws java.lang.Exception {
  30. zero(new int[] {1, 2, 1, 1});
  31. zero(new int[] {1, 2, 3, 4});
  32. zero(new int[] {1, 1, 2, 2});
  33. zero(new int[] {1, 1, 2});
  34. // your code goes here
  35. }
  36. }
  37.  
Success #stdin #stdout 0.1s 47124KB
stdin
Standard input is empty
stdout
[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
[1, 1, 2] is a zero array