Given an array\list containing integers, zero is considered an invalid number
and the rest of the other numbers are valid. If the two nearest valid numbers are equal
then double the value of the right one and make the left one 0.
ignore any comparison with zero
At last move all zeros to the right
Input:
2 4 5 0 0 5 5 4 8 6 0 6 8
Iteration Flow to understand the problem:
2 4 ....
2 4 5....
2 4 5 0 ...
2 4 5 0 0 .....
2 4 0 0 0 10 5...
2 4 0 0 0 10 5 4 8 0 0 12 8
Final Output Array:
2 4 10 5 4 8 12 8 0 0 0 0 0
<?php
// Your code here!
$arr = [2,4,5,0,0,5,5,4,8,6,0,6,8];
$arr_count = count($arr);
$res = [];
for ($i = 0, $j=0; $i < $arr_count-1; $i++) {
if($arr[$i]==0 && $i!=0){
$arr[$i] = $arr[$i-1];
$arr[$i-1] = 0;
}
else if($i!=0 && $arr[$i]!=0 && ($arr[$i] == $arr[$i-1])){
$arr[$i-1] = 0;
$arr[$i] = 2 * $arr[$i];
$i++;
}
print_r($arr[$i]);
}
No comments:
Post a Comment