Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given n item's value and label 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:
numWanted.useLimit.Return the maximum sum.
Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
Output: 9
Explanation:
The subset chosen is the first, third, and fifth items with the sum of values 5 + 3 + 1.
Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2
Output: 12
Explanation:
The subset chosen is the first, second, and third items with the sum of values 5 + 4 + 3.
Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1
Output: 16
Explanation:
The subset chosen is the first and fourth items with the sum of values 9 + 7.
Constraints:
n == values.length == labels.length1 <= n <= 2 * 1040 <= values[i], labels[i] <= 2 * 1041 <= numWanted, useLimit <= nProblem summary: You are given n item's value and label 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[5,4,3,2,1] [1,1,2,2,3] 3 1
[5,4,3,2,1] [1,3,3,3,2] 3 2
[9,8,8,7,6] [0,0,0,1,1] 3 1
maximize-ysum-by-picking-a-triplet-of-distinct-xvalues)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1090: Largest Values From Labels
class Solution {
public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
int n = values.length;
int[][] pairs = new int[n][2];
for (int i = 0; i < n; ++i) {
pairs[i] = new int[] {values[i], labels[i]};
}
Arrays.sort(pairs, (a, b) -> b[0] - a[0]);
Map<Integer, Integer> cnt = new HashMap<>();
int ans = 0, num = 0;
for (int i = 0; i < n && num < numWanted; ++i) {
int v = pairs[i][0], l = pairs[i][1];
if (cnt.getOrDefault(l, 0) < useLimit) {
cnt.merge(l, 1, Integer::sum);
num += 1;
ans += v;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1090: Largest Values From Labels
func largestValsFromLabels(values []int, labels []int, numWanted int, useLimit int) (ans int) {
n := len(values)
pairs := make([][2]int, n)
for i := 0; i < n; i++ {
pairs[i] = [2]int{values[i], labels[i]}
}
sort.Slice(pairs, func(i, j int) bool { return pairs[i][0] > pairs[j][0] })
cnt := map[int]int{}
for i, num := 0, 0; i < n && num < numWanted; i++ {
v, l := pairs[i][0], pairs[i][1]
if cnt[l] < useLimit {
cnt[l]++
num++
ans += v
}
}
return
}
# Accepted solution for LeetCode #1090: Largest Values From Labels
class Solution:
def largestValsFromLabels(
self, values: List[int], labels: List[int], numWanted: int, useLimit: int
) -> int:
ans = num = 0
cnt = Counter()
for v, l in sorted(zip(values, labels), reverse=True):
if cnt[l] < useLimit:
cnt[l] += 1
num += 1
ans += v
if num == numWanted:
break
return ans
// Accepted solution for LeetCode #1090: Largest Values From Labels
struct Solution;
use std::collections::HashMap;
type Pair = (i32, i32);
impl Solution {
fn largest_vals_from_labels(
values: Vec<i32>,
labels: Vec<i32>,
num_wanted: i32,
use_limit: i32,
) -> i32 {
let n = values.len();
let use_limit = use_limit as usize;
let mut num_wanted = num_wanted as usize;
let mut pairs: Vec<Pair> = values.into_iter().zip(labels.into_iter()).collect();
pairs.sort_unstable();
let mut hm: HashMap<i32, usize> = HashMap::new();
let mut res = 0;
for i in (0..n).rev() {
let count = hm.entry(pairs[i].1).or_default();
if *count < use_limit {
*count += 1;
res += pairs[i].0;
num_wanted -= 1;
}
if num_wanted == 0 {
break;
}
}
res
}
}
#[test]
fn test() {
let values = vec![5, 4, 3, 2, 1];
let labels = vec![1, 1, 2, 2, 3];
let num_wanted = 3;
let use_limit = 1;
let res = 9;
assert_eq!(
Solution::largest_vals_from_labels(values, labels, num_wanted, use_limit),
res
);
let values = vec![5, 4, 3, 2, 1];
let labels = vec![1, 3, 3, 3, 2];
let num_wanted = 3;
let use_limit = 2;
let res = 12;
assert_eq!(
Solution::largest_vals_from_labels(values, labels, num_wanted, use_limit),
res
);
let values = vec![9, 8, 8, 7, 6];
let labels = vec![0, 0, 0, 1, 1];
let num_wanted = 3;
let use_limit = 1;
let res = 16;
assert_eq!(
Solution::largest_vals_from_labels(values, labels, num_wanted, use_limit),
res
);
let values = vec![9, 8, 8, 7, 6];
let labels = vec![0, 0, 0, 1, 1];
let num_wanted = 3;
let use_limit = 2;
let res = 24;
assert_eq!(
Solution::largest_vals_from_labels(values, labels, num_wanted, use_limit),
res
);
}
// Accepted solution for LeetCode #1090: Largest Values From Labels
function largestValsFromLabels(
values: number[],
labels: number[],
numWanted: number,
useLimit: number,
): number {
const n = values.length;
const pairs = new Array(n);
for (let i = 0; i < n; ++i) {
pairs[i] = [values[i], labels[i]];
}
pairs.sort((a, b) => b[0] - a[0]);
const cnt: Map<number, number> = new Map();
let ans = 0;
for (let i = 0, num = 0; i < n && num < numWanted; ++i) {
const [v, l] = pairs[i];
if ((cnt.get(l) || 0) < useLimit) {
cnt.set(l, (cnt.get(l) || 0) + 1);
++num;
ans += v;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.