Minimum Deletions to Make Array Beautiful Problem
Description
LeetCode Problem 2216.
You are given a 0-indexed integer array nums. The array nums is beautiful if:
nums.lengthis even.nums[i] != nums[i + 1]for alli % 2 == 0.
Note that an empty array is considered beautiful.
You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.
Return the minimum number of elements to delete from nums to make it beautiful.
Example 1:
Input: nums = [1,1,2,3,5]
Output: 1
Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.
Example 2:
Input: nums = [1,1,2,2,3,3]
Output: 2
Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Greedy
A beautiful array has even length and, when cut into consecutive pairs, each pair holds two different numbers. Pairs may repeat values between them.
Scan from left to right, building pairs. If the current element equals the next one, delete one of them (count one deletion) and keep looking at the next element; otherwise, the two form a pair and we skip both.
When we are done, the number of elements kept might be odd, in which case one more deletion (the last element) is needed.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minDeletion(self, nums: List[int]) -> int:
n = len(nums)
i = ans = 0
while i < n - 1:
if nums[i] == nums[i + 1]:
ans += 1
i += 1
else:
i += 2
ans += (n - ans) % 2
return ans