Minimum Array Length After Pair Removals Problem
Description
LeetCode Problem 2856.
Given an integer array num sorted in non-decreasing order.
You can perform the following operation any number of times:
- Choose two indices,
iandj, wherenums[i] < nums[j]. - Then, remove the elements at indices
iandjfromnums. The remaining elements retain their original order, and the array is re-indexed.
Return the minimum length of nums after applying the operation zero or more times.
Example 1:
Input: nums = [1,2,3,4]
Output: 0
Explanation:

Example 2:
Input: nums = [1,1,2,2,3,3]
Output: 0
Explanation:

Example 3:
Input: nums = [1000000000,1000000000]
Output: 2
Explanation:
Since both numbers are equal, they cannot be removed.
Example 4:
Input: nums = [2,3,4,4,4]
Output: 1
Explanation:

Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9numsis sorted in non-decreasing order.
Solution
Approach: Greedy + Max Heap
Count how often each value occurs and put the counts into a max heap. A removed pair must consist of two different values, so repeatedly take the two largest counts, remove one occurrence of each (reduce both by one, pushing back any that are still positive), and shorten the array by 2. Pairing the most frequent values first leaves the fewest leftovers. Stop when fewer than two distinct values remain; the answer is the remaining length.
Complexity: Time O(n log n), space O(n).
from heapq import heapify, heappop, heappush
from collections import Counter
class Solution:
def minLengthAfterRemovals(self, nums: List[int]) -> int:
cnt = Counter(nums)
pq = [-x for x in cnt.values()]
heapify(pq)
ans = len(nums)
while len(pq) > 1:
x, y = -heappop(pq), -heappop(pq)
x -= 1
y -= 1
if x > 0:
heappush(pq, -x)
if y > 0:
heappush(pq, -y)
ans -= 2
return ans