LeetCode 2449. Minimum Number of Operations to Make Arrays Similar Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2449. Minimum Number of Operations to Make Arrays Similar

Description

You are given two positive integer arrays nums and target, of the same length.

In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:

  • set nums[i] = nums[i] + 2 and
  • set nums[j] = nums[j] - 2.

Two arrays are considered to be similar if the frequency of each element is the same.

Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.

 

Example 1:

Input: nums = [8,12,6], target = [2,14,10]
Output: 2
Explanation: It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = [10,12,4].
- Choose i = 1 and j = 2, nums = [10,14,2].
It can be shown that 2 is the minimum number of operations needed.

Example 2:

Input: nums = [1,2,5], target = [4,1,3]
Output: 1
Explanation: We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = [1,4,3].

Example 3:

Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0
Explanation: The array nums is already similiar to target.

 

Constraints:

  • n == nums.length == target.length
  • 1 <= n <= 105
  • 1 <= nums[i], target[i] <= 106
  • It is possible to make nums similar to target.

Solutions

Solution 1: Odd-Even Classification + Sorting

Notice that, because each operation will only increase or decrease the value of an element by 2, the parity of the element will not change.

Therefore, we can divide the arrays nums and target into two groups according to their parity, denoted as a1 and a2, and b1 and b2 respectively.

Then, we just need to pair the elements in a1 with the elements in b1, and pair the elements in a2 with the elements in b2, and then perform operations. During the pairing process, we can use a greedy strategy, pairing the smaller elements in ai with the smaller elements in bi each time, which can ensure the minimum number of operations. This can be directly implemented through sorting.

Since each operation can reduce the difference of the corresponding elements by 4, we accumulate the difference of each corresponding position, and finally divide by 4 to get the answer.

The time complexity is O(n × log n), where n is the length of the array nums.

PythonJavaC++GoTypeScript
class Solution: def makeSimilar(self, nums: List[int], target: List[int]) -> int: nums.sort(key=lambda x: (x & 1, x)) target.sort(key=lambda x: (x & 1, x)) return sum(abs(a - b) for a, b in zip(nums, target)) // 4(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !