Largest Values From Labels — LeetCode 1090 Python Solution

MediumGreedyArrayHash TableCountingSorting
Problem
#1090
Pattern
Greedy
Reading time
2 min

The problem

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1090. Largest Values From Labels is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1090. Largest Values From Labels?
LeetCode 1090. Largest Values From Labels is rated Medium on LeetCode.
What is the time complexity of LeetCode 1090. Largest Values From Labels?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1090. Largest Values From Labels?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1090. Largest Values From Labels cover?
LeetCode 1090. Largest Values From Labels is tagged Greedy, Array, Hash Table, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview