Array Partition

EasyGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums with an even length 2n. Split all the elements into n pairs (a1, b1), (a2, b2), ..., (an, bn) so that every element is used exactly once. The score of a split is the sum of min(ai, bi) over all pairs. Return the largest score you can achieve. Sorting-based solutions in O(n log n) are expected; a counting approach can reach O(n + range).

Examples

Input: nums = [1,4,3,2]
Output: 4
Pairing (1,2) and (3,4) gives 1 + 3 = 4, which is the best possible.
Input: nums = [6,2,6,5,1,2]
Output: 9
Pairs (1,2), (2,5), (6,6) give 1 + 2 + 6 = 9.

Constraints

  • 1 <= n <= 10^4
  • nums.length == 2 * n
  • -10^4 <= nums[i] <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems