Skip to content

Commit b704d61

Browse files
authored
Create advantage-shuffle.py
1 parent f705ea1 commit b704d61

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Python/advantage-shuffle.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
# Given two arrays A and B of equal size, the advantage of A with respect to B
5+
# is the number of indices i for which A[i] > B[i].
6+
#
7+
# Return any permutation of A that maximizes its advantage with respect to B.
8+
#
9+
# Example 1:
10+
#
11+
# Input: A = [2,7,11,15], B = [1,10,4,11]
12+
# Output: [2,11,7,15]
13+
# Example 2:
14+
#
15+
# Input: A = [12,24,8,32], B = [13,25,32,11]
16+
# Output: [24,32,8,12]
17+
#
18+
# Note:
19+
# - 1 <= A.length = B.length <= 10000
20+
# - 0 <= A[i] <= 10^9
21+
# - 0 <= B[i] <= 10^9
22+
23+
class Solution(object):
24+
def advantageCount(self, A, B):
25+
"""
26+
:type A: List[int]
27+
:type B: List[int]
28+
:rtype: List[int]
29+
"""
30+
sortedA = sorted(A)
31+
sortedB = sorted(B)
32+
33+
candidates = {b: [] for b in B}
34+
others = []
35+
j = 0
36+
for a in sortedA:
37+
if a > sortedB[j]:
38+
candidates[sortedB[j]].append(a)
39+
j += 1
40+
else:
41+
others.append(a)
42+
return [candidates[b].pop() if candidates[b] else others.pop()
43+
for b in B]

0 commit comments

Comments
 (0)