← 返回 walmartlabs 的题目列表Permutation Maximizing Σ B[i] where B[i] > A[i]
类型:qbank
Given two equal-length integer arrays A and B, choose a permutation of B that maximizes `s = Σ B[i] for indices where B[i] > A[i]`. Return that maximum.
Requirements
Input: A: int[], B: int[] with len(A) == len(B) == n.
For any permutation of B, define s = Σ_{i : B[i] > A[i]} B[i]. Return the maximum s over all permutations of B.
Constraints reported as moderate (n such that O(n²) is too slow; aim for O(n log n)).
Examples
Worked example: A = [2, 5, 3], B = [4, 6, 1].
Try aligning sorted-asc A with sorted-asc B and greedily assign the smallest B-element that still beats the current A-element; carry leftovers to indices where they can never qualify. Optimal assignment here yields B = [4, 6, 1] placed against A as B[0]=4>A[0]=2, B[1]=6>A[1]=5, B[2]=1≤A[2]=3 → s = 4+6 = 10.
Notes
Greedy two-pointer on sorted arrays: sort A ascending; sort B ascending; walk a pointer j over B. For each A[i] in ascending order, advance j to the smallest B-value strictly greater than A[i]; assign that B-value to this A-index (contributes to s), then move on. Unassigned B-values get parked at A-indices where they could not have qualified anyway (they contribute zero).
Equivalent framing: this is the "advantage shuffle" (LC 870) family — find the maximum matching in a bipartite graph where edges connect B[j] > A[i], weighted by B[j]. The greedy is optimal because preferring the smallest qualifying B for each A frees the larger Bs for harder-to-beat As.
Total complexity O(n log n) from the sorts; the sweep itself is linear.
An off-by-one to watch: strictly greater (>), not >=. Candidates who use >= will get the wrong answer on cases with ties.
Preparation
Implement the sort + two-pointer skeleton from memory in under five minutes; it generalizes to several similar OA prompts (advantage shuffle, fair-pairing).
Walk through the proof of greedy optimality verbally before coding — the OA does not require a proof, but it builds the right invariant in your head and prevents off-by-one bugs.
Cover the three test patterns: A and B disjoint sorted ranges (all positions qualify), heavy ties in A (forces strict-greater handling), and max(B) ≤ min(A) (answer 0).
This is the most algorithmically loaded item on the current OA; budget 40 of the 90 minutes for it.