K Items With the Maximum Sum — LeetCode 2600 Python Solution

EasyGreedyMath
Problem
#2600
Pattern
Greedy
Reading time
2 min

The problem

There is a bag that consists of items, each item has a number 1, 0, or -1 written on it. You are given four non-negative integers numOnes, numZeros, numNegOnes, and k.

Example

Input
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2
Output
2
Explanation
We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2.

Python solution

Python
class Solution:
    def kItemsWithMaximumSum(
        self, numOnes: int, numZeros: int, numNegOnes: int, k: int
    ) -> int:
        if numOnes >= k:
            return k
        if numZeros >= k - numOnes:
            return numOnes
        return numOnes - (k - numOnes - numZeros)

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2600. K Items With the Maximum Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

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 2600. K Items With the Maximum Sum?
LeetCode 2600. K Items With the Maximum Sum is rated Easy on LeetCode.
What is the time complexity of LeetCode 2600. K Items With the Maximum Sum?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 2600. K Items With the Maximum Sum?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2600. K Items With the Maximum Sum cover?
LeetCode 2600. K Items With the Maximum Sum is tagged Greedy and Math 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