Choose exactly items from a bag containing $1, \0-1$ values to maximize the total sum.
K Items With The Maximum Sum
You are given three integers numOnes, numZeros, and numNegOnes, which represent how many items with values 1, 0, and -1 are available. You must pick exactly k items from this collection.
Your goal is to maximize the sum of the values of the chosen items.
Return the maximum possible sum.
The order of picking does not matter. You may choose any valid combination of available items as long as exactly k items are selected.
Input Format
- Three counts are given:
numOnes,numZeros, andnumNegOnes. - An integer
kspecifies how many items must be chosen. - The available multiset contains:
numOnesitems of value1numZerositems of value0numNegOnesitems of value-1
Output Format
- Return a single integer: the maximum sum achievable by selecting exactly
kitems.
Constraints
0 <= numOnes, numZeros, numNegOnes <= $10^{5}$0 <= k <= numOnes + numZeros + numNegOnes- Exactly
kitems must be selected.
Example 1
Input
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2
Output
2
Explanation
Pick two 1s for the largest possible sum: 1 + 1 = 2.
Example 2
Input
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
Output
3
Explanation
Pick all three 1s and one 0: 1 + 1 + 1 + 0 = 3.
Show 1 more example
Example 3
Input
numOnes = 1, numZeros = 1, numNegOnes = 3, k = 3
Output
0
Explanation
Pick 1, 0, and one -1: 1 + 0 - 1 = 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.