Minimum Number of Operations to Make Arrays Similar — LeetCode 2449 Python Solution

HardGreedyArraySorting
Problem
#2449
Pattern
Greedy
Reading time
2 min

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

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array nums
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview