Magicsheet logo

Largest Values From Labels

Medium
12.5%
Updated 8/1/2025

Largest Values From Labels

1. What is this problem about?

In the Largest Values From Labels coding problem, you are given two arrays: values and labels. Each value has a corresponding label. You need to select a subset of items such that the number of items is at most numWanted, and for any given label, you use at most useLimit items with that label. Your goal is to maximize the sum of the values in your subset.

2. Why is this asked in interviews?

Amazon and Google ask this problem to evaluate a candidate's ability to handle multi-constraint optimization. It tests your proficiency in using multiple data structures (like Hash Tables for counting and sorting for greedy selection) in tandem. It requires a clear understanding of the "Greedy" principle—taking the best available option that doesn't violate your constraints.

3. Algorithmic pattern used

This problem follows the Sorting and Greedy interview pattern. The strategy is to pair each value with its label and sort these pairs by value in descending order. Then, iterate through the sorted pairs. For each pair, check if you've already used useLimit items for that label (using a Hash Table to keep track of counts). If not, add the value to your total sum, increment the label count, and decrease the numWanted quota.

4. Example explanation

Values: [5, 4, 3, 2, 1], Labels: [1, 1, 2, 2, 3], numWanted: 3, useLimit: 1.

  1. Pairs (Value, Label): (5,1), (4,1), (3,2), (2,2), (1,3). (Already sorted).
  2. Take (5,1). Label 1 count: 1. Total: 5. (Remaining numWanted: 2).
  3. Look at (4,1). Label 1 count is already 1 (the limit). Skip.
  4. Take (3,2). Label 2 count: 1. Total: 5 + 3 = 8. (Remaining numWanted: 1).
  5. Look at (2,2). Label 2 count is already 1. Skip.
  6. Take (1,3). Label 3 count: 1. Total: 8 + 1 = 9. (Remaining numWanted: 0). Final sum: 9.

5. Common mistakes candidates make

A common error is not sorting the values first, which is essential for the greedy strategy to work. Another mistake is forgetting the two different limits: the global numWanted and the per-label useLimit. Some candidates also struggle with how to efficiently pair values with labels before sorting.

6. Interview preparation tip

When you encounter "Greedy, Sorting interview pattern" problems with multiple constraints, always think about which constraint is the most "expensive." Sorting by value allows you to always prioritize the largest contribution to your sum, while the Hash Table manages the secondary "label" constraint.

Similar Questions