繁体   English   中英

与 arrays arr1 和 arr2 匹配的最小移动次数)

[英]minimum number of moves to match the arrays arr1 and arr2)

有两个整数 arr1 和 arr2 的 arrays。 一次移动定义为数组中项目的每个数字之一的增量或减量。 将数组 arr1 与数组 arr2 匹配需要多少次移动? 不允许对数字进行重新排序。

例子

arr1 = [123, 543]

arr2 = [321, 279]

Match arr1[0]=123 with arr2[0]=321.
Increment 1 twice to get 3 (2 moves) and decrement 3 twice to get 1 (2 moves).
4 moves are needed to match 123 with 321.
Match arr1[1]=543 with arr2[1]=279.
Decrement 5 three times to get 2 (3 moves) and increment 4 three times to get 7 (3 moves) and increment 3 six times to get 9 (6 moves).
12 moves are needed to match 543 with 279.
16 total moves are needed to match the arrays arr1 and arr2.

约束

1 ≤ n ≤ 105
1 ≤ arr1[i], arr2[i] ≤ 109
The lengths of arr1 and arr2 are equal, |arr1| = |arr2|.
The elements arr1[i] and arr2[i] have an equal number of digits.

示例案例 0

样本输入

STDIN Function

----- --------

2 → n = 2

1234 → arr1 = [1234,4321]

4321

2 → n = 2

2345 → arr2 = [2345,3214]

3214

样品 Output

10

解释

Match arr1[0]=1234 with arr2[0]=2345.
Increment 1 once to get 2 (1 move) and increment 2 once to get 3 (1 move)  Increment 3 once to get 4 (1 move)  and increment 4 once to get 5 (1 move).
4 moves are needed to match 1234 with 2345.
Match arr1[1]=4321 with arr2[1]=3214.
Decrement 4 once to get 3 (1 move) and decrement 3 once to get 2 (1 move) and decrement 2 once to get 1 (1 move) and increment 1 three times to get 3 (3 moves)
6 moves are needed to match 4321 with 3214.
6+4=10 total moves are needed to match the arrays arr1 and arr2.

案例一

样本输入

STDIN Function

----- --------

1 → n = 1

2468 → arr1 = [2468]

1 → n = 1

8642 → arr2 = [8642]

样品 Output

16

解释

Match arr1[0]=2468 with arr2[0]=8642.
Increment 2 six times to get 8 (6 moves). Increment 4 twice to get 6 (2 moves). Decrement 6 twice to get 4 (2 moves). Decrement 8 six times to get 2  (6 moves).
16 moves are needed to match the arrays arr1 and arr2.

:-

$a = [2468];
$b = [8642];
$n = count($a);

$result = 0; 

for ($i = 0; $i < $n; $i++)  
{ 
  $n1 = $a[$i]; 
  $n2 = $b[$i]; 
  while($n1 !=0){
     $r1 = $n1 % 10;
     $r2 = $n2 % 10;
     $n1 = $n1 /10;
     $n2 = $n2 /10;
     if($r1 > $r2){
         $result = $result + abs($r1 - $r2); 
     }
     if($r2 > $r1){
       $result = $result + abs($r2 - $r1); 
     }

  }

} 

echo  $result;

我不知道我错在哪里所以请帮助我

将数字拆分为数字的 arrays 并找到对应数字之间的正差

$arr1 = [1234,4321];
$arr2 = [2345,3214];

$sum = 0;
foreach(array_map(null, $arr1, $arr2) as list($x, $y)) {
    $x = str_split($x);
    $y = str_split($y);
    foreach(array_map(null, $x, $y) as list($a, $b)) {
        $sum += abs($a-$b);
    }
}
print($sum); // 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM