Created
May 28, 2021 04:10
-
-
Save kangmasjuqi/ddec6199ce1555da957926174c908033 to your computer and use it in GitHub Desktop.
HACKERRANK-TEST-2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// HACKERRANK-TEST-2 | |
// | |
// Question : https://imgur.com/QI2hoR0 | |
/* | |
* Complete the 'minDiff' function below. | |
* | |
* The function is expected to return an INTEGER. | |
* The function accepts INTEGER_ARRAY arr as parameter. | |
*/ | |
// | |
// https://www.ma-no.org/ | |
// | |
function shellSort($array) | |
{ | |
if (!$length = count($array)) { | |
return $array; | |
} | |
$k = 0; | |
$gap[0] = (int)($length/2); | |
while($gap[$k]>1){ | |
$k++; | |
$gap[$k] = (int)($gap[$k-1]/2); | |
} | |
for ($i = 0; $i <=$k; $i++) { | |
$step = $gap[$i]; | |
for ($j = $step; $j<$length; $j++) { | |
$temp = $array[$j]; | |
$p = $j-$step; | |
while ($p >=0 &&$temp < $array[$p]) { | |
$array[$p+$step] = $array[$p]; | |
$p = $p-$step; | |
} | |
$array[$p+$step] = $temp; | |
} | |
} | |
return $array; | |
} | |
function minDiff($arr) { | |
// sorting | |
$n = count($arr); | |
$arr = shellSort($arr); | |
$diff = 0; | |
for($ii=0;$ii<$n-1;$ii++){ | |
$diff += abs($arr[$ii] - $arr[$ii+1]); | |
} | |
return $diff; | |
} | |
$fptr = fopen(getenv("OUTPUT_PATH"), "w"); | |
$arr_count = intval(trim(fgets(STDIN))); | |
$arr = array(); | |
for ($i = 0; $i < $arr_count; $i++) { | |
$arr_item = intval(trim(fgets(STDIN))); | |
$arr[] = $arr_item; | |
} | |
$result = minDiff($arr); | |
fwrite($fptr, $result . "\n"); | |
fclose($fptr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment