簡體   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