Classic problem #2600EasyMathGreedy
K Items With the Maximum Sum
Real-world version: Best Handful From the Token TinTracked in this browser only
Read K Items With the Maximum Sum on LeetCode(opens in a new tab)
The statement here is our own: the same inputs, outputs and technique.
A tin holds numOnes tokens marked 1, numZeros marked 0 and numNegOnes marked -1.
Take exactly k tokens out of the tin. Return the largest total the marks on those tokens can come to.
Examples
Example 1
- Input
- numOnes = 7, numZeros = 4, numNegOnes = 6, k = 13
- Output
- 5
Taking all seven ones and all four zeros accounts for eleven tokens, so the last two must be negatives, giving 7 less 2.
Example 2
- Input
- numOnes = 3, numZeros = 4, numNegOnes = 0, k = 5
- Output
- 3
All three ones fit and the remaining two tokens are zeros, so nothing pulls the total down.
Example 3
- Input
- numOnes = 0, numZeros = 0, numNegOnes = 9, k = 9
- Output
- -9
The tin holds nothing but negatives and all nine must come out.
Constraints
- 0 <= numOnes <= 50
- 0 <= numZeros <= 50
- 0 <= numNegOnes <= 50
- 0 <= k <= numOnes + numZeros + numNegOnes
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
Python
def k_items_with_maximum_sum(numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:Java
public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Minimum Cost to Move Chips to The Same PositionReal-world version: Shunting Pallets Into One BayEasy
- Minimum Number of Pushes to Type Word IReal-world version: Eight-Key Field TerminalEasy
- Largest Odd Number in StringReal-world version: Largest Odd Segment of a SerialEasy
- Distribute Money to Maximum ChildrenReal-world version: Badges at the Token CounterEasy