Skip to content

Instantly share code, notes, and snippets.

@ryanwinchester
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwinchester/0e546d21c3d42807f709 to your computer and use it in GitHub Desktop.
Save ryanwinchester/0e546d21c3d42807f709 to your computer and use it in GitHub Desktop.
Codility TapeEquality O(n)
<?php
/**
* @param array $A
* @return int
*/
function solution(array $A)
{
$left = $A[0];
$right = array_sum($A) - $left;
$min = abs($left - $right);
$keys = count($A);
for ($i = 1; $i < $keys - 1; $i++) {
$left += $A[$i];
$right -= $A[$i];
$diff = abs($left - $right);
$min = ($diff < $min) ? $diff : $min;
}
return $min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment