[
sort
greedy
array
two pointers
]
Leetcode 0870. Advantage Shuffle
https://leetcode.com/problems/advantage-shuffle
The idea here is to sort A
and B
lists first and start with the biggest number from B
and check if we can beat it with biggest number from A
. If we can, do it and increase beg
pointer. If no, than we need to choose the smallest number we have and we move end
pointer. One difficulty here is that we need to keep order of data somehow, so we add indexes to B
list. Then we create ans
list and change corresponding element of it.
Time complexity is O(n log n)
to perform sorts and space complexity is O(n)
.
class Solution:
def advantageCount(self, A, B):
n = len(A)
B = sorted([(num, i) for i, num in enumerate(B)])[::-1]
A = sorted(A)[::-1]
ans = [-1]*n
beg, end = 0, n - 1
for num, ind in B:
if A[beg] > num:
ans[ind] = A[beg]
beg += 1
else:
ans[ind] = A[end]
end -= 1
return ans
If you like the solution, you can upvote it on leetcode discussion section: Problem 0870