Problem Description
Given an array of integers, the goal is to delete the minimum number of elements so that the resulting array is "beautiful." An array is considered beautiful if its length is even and for every even index i (0-indexed), the element at nums[i] is not equal to its immediate next element nums[i+1]. Note that an empty array is also considered beautiful.
Key Insights
- Use a greedy approach to simulate the construction of a beautiful array.
- Iterate through the array while forming valid pairs.
- If adding an element would cause a pair violation (i.e., both elements in a pair are the same), skip that element (count it as a deletion).
- After processing, if the length of the constructed array is odd, remove the last element to satisfy the even-length condition.
Space and Time Complexity
Time Complexity: O(n) - We traverse the input array once. Space Complexity: O(n) - In the worst-case scenario, we may store nearly all elements in our simulation (this can be optimized to O(1) by just tracking counts).
Solution
We can solve this problem by simulating the construction of a "beautiful" array. Initialize an empty result list and a deletion counter. Loop through the input array; add the current element if it does not cause an even-index pair to have identical elements. If it would, consider it deleted (increment deletion counter). Finally, if the resulting list has an odd number of elements, remove the last element and increase the deletion counter by one to ensure an even count.