Minimum Number of Operations to Make Arrays Similar — LeetCode 2449 Python Solution
- Problem
- #2449
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [8,12,6], target = [2,14,10]
- Output
- 2
- Explanation
- It is possible to make nums similar to target in two operations:
Python solution
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)) // 4Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the length of the array nums |
| Space | O(1) to O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2449. Minimum Number of Operations to Make Arrays Similar is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2449. Minimum Number of Operations to Make Arrays Similar?
- LeetCode 2449. Minimum Number of Operations to Make Arrays Similar is rated Hard on LeetCode.
- What topics does LeetCode 2449. Minimum Number of Operations to Make Arrays Similar cover?
- LeetCode 2449. Minimum Number of Operations to Make Arrays Similar is tagged Greedy, Array and Sorting on LeetCode.