MediumNo. 1090

Largest Values From Labels — LeetCode 1090 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Hash Table, Counting, Sorting
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0621Task SchedulerMedium
1054Distant BarcodesMedium
1481Least Number of Unique Integers after K RemovalsMedium
0169Majority ElementEasy
0229Majority Element IIMedium
0347Top K Frequent ElementsMedium

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.

Free to download. Check it runs on your machine, then pick a plan.