K Items With the Maximum Sum - 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.
The bag initially contains:
numOnesitems with1s written on them.numZerositems 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.
Input & Output
Example 1 — Basic Greedy Selection
$
Input:
numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
›
Output:
3
💡 Note:
Take all 3 items with value 1, then 1 item with value 0. Total sum = 3×1 + 1×0 = 3
Example 2 — Need Negative Items
$
Input:
numOnes = 3, numZeros = 2, numNegOnes = 1, k = 6
›
Output:
2
💡 Note:
Take all 3 ones, all 2 zeros, and 1 negative one. Total sum = 3×1 + 2×0 + 1×(-1) = 2
Example 3 — Only Ones Needed
$
Input:
numOnes = 5, numZeros = 3, numNegOnes = 2, k = 3
›
Output:
3
💡 Note:
Only need 3 items, take 3 ones. Total sum = 3×1 = 3
Constraints
- 0 ≤ numOnes, numZeros, numNegOnes ≤ 50
- 1 ≤ k ≤ numOnes + numZeros + numNegOnes ≤ 50
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code