You are given two integer arrays nums1
and nums2
both of the same length. The advantage of nums1
with respect to nums2
is the number of indices i
for which nums1[i] > nums2[i]
.
Return any permutation of nums1
that maximizes its advantage with respect to nums2
.
Example 1:
Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] Output: [2,11,7,15]
Example 2:
Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11] Output: [24,32,8,12]
Constraints:
1 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 109
The problem asks to find a permutation of nums1
that maximizes the advantage over nums2
. The advantage is defined as the number of indices where nums1[i] > nums2[i]
. This can be solved efficiently using a greedy approach combined with sorting.
Approach:
Sort: Sort both nums1
(ascending) and create a sorted array of pairs (nums2[i], i)
(ascending by nums2[i]
). The pairs keep track of the original index in nums2
.
Two Pointers: Use two pointers, i
and j
. i
points to the smallest element in the sorted nums2
(from the pair array). j
points to the largest element in the sorted nums1
.
Greedy Assignment: Iterate through nums1
. For each element v
in nums1
:
v > t[i][0]
(where t[i][0]
is the value of nums2
at index i
and t
is the sorted array of pairs), it means we can use v
to beat the current smallest element in nums2
. Assign v
to the position t[i][1]
(the original index in nums2
). Increment i
.v
is smaller than or equal to the smallest remaining element in nums2
. We assign it to the position t[j][1]
(the original index of the largest element in nums2
that's still unassigned). Decrement j
. This strategy minimizes the damage when we cannot win.Return: The resulting ans
array is a permutation of nums1
that maximizes the advantage.
Time Complexity Analysis:
nums1
and creating the sorted pairs array t
takes O(N log N) time, where N is the length of the arrays.Space Complexity Analysis:
t
and the ans
array. Both have size O(N).Code Examples (Python, Java, C++, Go, TypeScript, Rust): The provided code snippets in the different languages all implement this approach. They differ slightly in syntax and data structures, but the underlying algorithm remains the same. The comments in each code snippet should make it easy to follow the steps of the algorithm. The Python and Java examples were already provided in your question, I have added more.
This solution efficiently finds a permutation of nums1
that maximizes the advantage against nums2
with optimal time and space complexity.