K Items With the Maximum Sum Problem
#2600
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2600.
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.
The bag initially contains:
numOnesitems with1s written on them.numZeroesitems with0s written on them.numNegOnesitems with-1s written on them.
We want to pick exactly k items among the available items. Return the maximum possible sum of numbers written on the items.
Example 1:
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.
It can be proven that 2 is the maximum possible sum.
Example 2:
Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
Output: 3
Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3.
It can be proven that 3 is the maximum possible sum.
Constraints:
0 <= numOnes, numZeros, numNegOnes <= 500 <= k <= numOnes + numZeros + numNegOnes
Solution
Approach: Greedy
Take items in order of value: first the 1s, then the 0s, then the -1s.
- If
numOnes >= k, allkitems are1s and the sum isk. - Otherwise take all
numOnesof them. If there are at leastk - numOneszeros, the rest are zeros and the sum staysnumOnes. - Otherwise the remaining
k - numOnes - numZerositems are-1s, so the sum isnumOnes - (k - numOnes - numZeros).
Complexity: time O(1), space O(1).
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)