Largest Values From Labels - Problem
You are given n items with their values and labels as two integer arrays values and labels. You are also given two integers numWanted and useLimit.
Your task is to find a subset of items with the maximum sum of their values such that:
- The number of items is at most
numWanted - The number of items with the same label is at most
useLimit
Return the maximum sum.
Input & Output
Example 1 — Basic Selection
$
Input:
values = [5,4,3,2], labels = [1,0,0,1], numWanted = 3, useLimit = 1
›
Output:
9
💡 Note:
Sort by values: (5,1), (4,0), (3,0), (2,1). Pick (5,1) and (4,0). Can't pick (3,0) because label 0 already used once. Result: 5+4=9
Example 2 — Constraint Limiting
$
Input:
values = [5,4,3,2], labels = [1,0,0,1], numWanted = 2, useLimit = 1
›
Output:
9
💡 Note:
Same sorting, but numWanted=2 limits us to 2 items. Pick highest values (5,1) and (4,0). Result: 5+4=9
Example 3 — High Use Limit
$
Input:
values = [9,8,8,7], labels = [0,0,0,1], numWanted = 3, useLimit = 2
›
Output:
25
💡 Note:
Sort: (9,0), (8,0), (8,0), (7,1). Pick first 3: 9+8+8=25. useLimit=2 allows 2 items with label 0
Constraints
- 1 ≤ values.length == labels.length ≤ 2 × 104
- 0 ≤ values[i], labels[i] ≤ 2 × 104
- 1 ≤ numWanted, useLimit ≤ values.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Items with values and labels, plus constraints
2
Process
Sort by value and greedily select best items
3
Output
Maximum possible sum
Key Takeaway
🎯 Key Insight: Greedy selection works because we want maximum value and constraints are independent - sort by value and pick greedily
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code