Largest Values From Labels

MediumGreedygreedy

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

There are n items. Item i has a score values[i] and a category labels[i]. Pick a subset of items such that the subset has at most numWanted items and no category appears more than useLimit times in it. Return the largest possible total score of such a subset. The empty subset is allowed (its total is 0).

Examples

Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
Output: 9
Take the items with scores 5 (label 1), 3 (label 2) and 1 (label 3).
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1
Output: 16
Only one item per label is allowed, so take 9 (label 0) and 7 (label 1).

Constraints

  • 1 <= n <= 2 * 10^4
  • values.length == labels.length == n
  • 0 <= values[i], labels[i] <= 2 * 10^4
  • 1 <= numWanted, useLimit <= n

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