Problem Description
Given a 0-indexed integer array nums, you can repeatedly pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j] and mark both indices. The task is to maximize the total number of marked indices using the allowed operations and return that maximum count.
Key Insights
- Sorting the array simplifies the process of finding valid pairs.
- A two-pointer or greedy strategy helps in efficiently matching smaller numbers with the next available number that is at least twice as large.
- Splitting the sorted array into two halves and trying to pair elements from the first half with elements in the second half is a common tactic.
- The solution is based on pairing elements greedily to maximize the number of valid operations.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(n) (or O(1) extra space if sorting is done in place).
Solution
The solution follows these steps:
- Sort the array.
- Use two pointers: one (left) starting at the beginning of the array and the other (right) starting roughly at the middle.
- For each candidate from the left pointer, find the smallest candidate from the right pointer that satisfies 2 * nums[left] <= nums[right].
- If a valid pair is found, increase both pointers accounting for a full pair marked.
- Continue until either pointer runs out of eligible elements.
- The maximum number of marked indices is twice the number of valid pairs found.
This two-pointer approach ensures that every time a valid pair is made, we are making a greedy choice that maximizes the overall pairing, leading to an optimal solution.