fork download
  1. /**
  2.  * Find the index in an array where sum to left is equal to sum to its right
  3.  * @author PRATEEK
  4.  */
  5. class EquilibriumIndex {
  6.  
  7. /**
  8. * @param arr: input arr
  9. * @return : equilibrium index in the array
  10. */
  11. private int equilibrium(int[] arr) {
  12. int i = 0, sum = 0, rightSum = 0;
  13. for (; i < arr.length; sum += arr[i++]);
  14.  
  15. for (i--; i > 0; sum -= arr[i], rightSum += arr[i])
  16. if (sum == rightSum - arr[i--])
  17. return i;
  18.  
  19. return -1;
  20. }
  21.  
  22. public static void main(String[] args) {
  23.  
  24. int arr[] = { -7, 1, 6, 2, -4, 3, 1 };
  25. EquilibriumIndex obj = new EquilibriumIndex();
  26. int mid = obj.equilibrium(arr);
  27. System.out.println(mid);
  28.  
  29. }
  30. }
  31.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
3