Skip to content

Instantly share code, notes, and snippets.

@barakpinchovski
Last active November 24, 2021 10:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barakpinchovski/89e7739641a80719521f61954b90025d to your computer and use it in GitHub Desktop.
Save barakpinchovski/89e7739641a80719521f61954b90025d to your computer and use it in GitHub Desktop.
<?php
$q = [2,1,5,3,4];
minimumBribes($q);
function minimumBribes($q) {
$no_ans = 'Too chaotic';
$ans = 0;
if (gettype($q) !== 'array' || !count($q)) {
return $no_ans;
}
$len = count($q);
end($q);
prev($q);
while ($currVal = current($q)) {
$currKey = key($q) + 1;
$positionDiff = $currVal - $currKey;
if ($positionDiff > 2) {
echo $no_ans . PHP_EOL;
return;
}
elseif ($positionDiff > 0) {
shift_arr_values($q, key($q), key($q) + $positionDiff);
$ans += $positionDiff;
}
else {
prev($q);
}
}
echo $ans . PHP_EOL;
return;
}
function shift_arr_values(&$arr, $i, $j) {
$temp = $arr[$i];
for ($s = $i; $s < $j; $s++) {
$arr[$s] = $arr[$s + 1];
}
$arr[$j] = $temp;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment