Largest Values From Labels - Problem
Imagine you're a treasure hunter with a collection of valuable items, each marked with different labels indicating their categories. You want to maximize your treasure value, but there are two important constraints:
- Limited bag space: You can only carry at most
numWanteditems - Category diversity: You can't take more than
useLimititems from the same category (label)
Given two arrays:
values- the value of each itemlabels- the category label of each item
Your goal is to select a subset of items that maximizes the total value while respecting both constraints.
Example: If you have items with values [5,4,3,2,1] and labels [1,1,2,2,3], and you want at most 3 items with at most 1 item per label, you'd pick the items with values 5, 3, and 1 (one from each label) for a total of 9.
Input & Output
example_1.py โ Basic Selection
$
Input:
values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
โบ
Output:
9
๐ก Note:
We can select items with values 5 (label 1), 3 (label 2), and 1 (label 3). Each label appears at most once, and we selected exactly 3 items for a total of 9.
example_2.py โ Multiple Items Per Label
$
Input:
values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2
โบ
Output:
12
๐ก Note:
We can select items with values 5 (label 1), 4 (label 3), and 3 (label 3). Label 3 appears twice which is within the limit of 2, giving us a total of 12.
example_3.py โ Limited by numWanted
$
Input:
values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 2, useLimit = 3
โบ
Output:
17
๐ก Note:
We can select items with values 9 and 8 (both label 0). Even though useLimit allows 3 items per label, numWanted limits us to 2 items total, giving us 9 + 8 = 17.
Constraints
- 1 โค values.length == labels.length โค 2 * 104
- 0 โค values[i], labels[i] โค 2 * 104
- 1 โค numWanted, useLimit โค values.length
- All values and labels are non-negative integers
Visualization
Tap to expand
Understanding the Visualization
1
Sort Treasures by Value
Arrange all treasures from most valuable to least valuable - this ensures we always consider the best options first
2
Greedy Selection
Go through treasures in order, picking each one if it doesn't violate our constraints (bag space and category limits)
3
Track Constraints
Keep count of items per category and total items selected to ensure we never violate the rules
Key Takeaway
๐ฏ Key Insight: The greedy approach works because once items are sorted by value, selecting the highest available value that doesn't violate constraints is always the optimal choice. There's no advantage to saving space for lower-value items.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code