#1090

Largest Values From Labels

Medium
ArrayHash TableGreedySortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution sorts the items by value and uses a greedy approach to select the highest values while respecting the label limits. This is efficient and leverages a hash map to track how many items from each label are selected.

⚙️

Algorithm

3 steps
  1. 1Step 1: Pair each value with its corresponding label and sort the pairs by value in descending order.
  2. 2Step 2: Initialize a hash map to count the number of items selected for each label.
  3. 3Step 3: Iterate through the sorted pairs, adding values to the sum while respecting numWanted and useLimit constraints.
solution.py12 lines
1def largestValuesFromLabels(values, labels, numWanted, useLimit):
2    items = sorted(zip(values, labels), key=lambda x: -x[0])
3    label_count = {}
4    total_sum = 0
5    count = 0
6    for value, label in items:
7        if count < numWanted:
8            if label_count.get(label, 0) < useLimit:
9                label_count[label] = label_count.get(label, 0) + 1
10                total_sum += value
11                count += 1
12    return total_sum

Complexity note: The time complexity is O(n log n) due to the sorting step, which is efficient for the input size. The space complexity is O(n) because we store the items in a list.

  • 1Sorting items by value allows for a greedy selection of the highest values.
  • 2Using a hash map to track label counts helps enforce the useLimit constraint.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.