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: 24
💡 Note: Sort: (9,0), (8,0), (8,0), (7,1). Pick (9,0) and (8,0) - now label 0 is at useLimit=2. Pick (7,1). Result: 9+8+7=24

Constraints

  • 1 ≤ values.length == labels.length ≤ 2 × 104
  • 0 ≤ values[i], labels[i] ≤ 2 × 104
  • 1 ≤ numWanted, useLimit ≤ values.length

Visualization

Tap to expand
Largest Values From Labels INPUT values[] 5 4 3 2 idx:0 idx:1 idx:2 idx:3 labels[] 1 0 0 1 numWanted = 3 useLimit = 1 Items (value, label): v:5 L:1 v:4 L:0 v:3 L:0 v:2 L:1 ALGORITHM STEPS 1 Sort by Value (DESC) Pair items, sort descending 5,1 4,0 3,0 2,1 2 Track Label Usage Use hashmap for counts labelCount: {0:0, 1:0} 3 Greedy Selection Pick if count < useLimit [OK] 5,L1 --> sum=5 [OK] 4,L0 --> sum=9 [X] 3,L0 limit reached [X] 2,L1 limit reached 4 Return Sum Stop at numWanted items items=2, sum=9 FINAL RESULT Selected Items: Item 0 val=5, L=1 Item 1 val=4, L=0 Rejected Items: val=3, L=0 L0 limit hit val=2, L=1 L1 limit hit Calculation: 5 + 4 = 9 (2 items, each label used 1x) Output: 9 Key Insight: Greedy works because sorting by value ensures we always pick the highest-value items first. The useLimit constraint prevents using too many items with the same label, and numWanted limits total items. Time Complexity: O(n log n) for sorting. Space: O(n) for storing pairs and label counts. TutorialsPoint - Largest Values From Labels | Greedy Approach
Asked in
Google 15 Amazon 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen