diff --git a/EquilibriumIndex.php b/EquilibriumIndex.php index 020dd2b..233970e 100644 --- a/EquilibriumIndex.php +++ b/EquilibriumIndex.php @@ -1,9 +1,54 @@ =0){ + $left_acum += $arr[$index-1]; + } + + // We start knowing the value of adding all the elements on the array ($arr), so if we start on the + // element on the left (index 0) and we substract its value from the sum of all array elements , we + // are going to get a value that represents the sum of all elements on the array minus the value of the + // element on index 0. If we store that last value and we keep substracting each array value, one by one,from left to right,on each iteration we get the sum of all elements to the right of the current index. + $right_acum -= $arr[$index]; + + // If the sum of elements on the left is equal to the sum of elements to the right then this index is known + // as an equilibrium index and needs to be added to the return values. + if ($left_acum==$right_acum){ + // An array can have more than one equilibrium indexes, so add the equilibrium index to the + // array that is going to be returned. + $output[]=$index; + } + } + } return $output; }