K Items With the Maximum Sum — LeetCode 2600 Python Solution
- Problem
- #2600
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(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.