Problem Description
Given two integer arrays nums1 and nums2 of the same length, rearrange (permute) nums1 such that the number of indices i where nums1[i] > nums2[i] is maximized. Return any permutation of nums1 that achieves this maximum advantage.
Key Insights
- Sort nums1 so you can greedily pick the smallest or largest values as needed.
- Sort nums2 along with their original indices to preserve ordering of results.
- Use a two-pointers strategy: assign the largest nums1 value that can beat the current largest nums2 value; if not, assign the smallest available nums1 value to sacrifice the matchup.
- This greedy approach ensures optimal pairing to maximize the advantage count.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the arrays
Space Complexity: O(n) for auxiliary arrays used to store indices and results
Solution
First, sort nums1 and create a sorted version of nums2 that contains both values and their original indices. Then, iterate in reverse through the sorted nums2 array while maintaining two pointers on nums1: one (high) starting at the end (largest numbers) and one (low) starting at the beginning (smallest numbers).
- If the current largest element in nums1 beats the current value in nums2, assign it to win that matchup and decrement the high pointer.
- Otherwise, assign the smallest available element from nums1 to minimize loss (sacrifice) and increment the low pointer.
After processing, the result is placed back in the order corresponding to the original indices in nums2.