All problems
0903EasyMathGreedy

Best Handful From the Token Tin

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2600K Items With the Maximum Sum

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a 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)
September 7
Apply