Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Greedy
K Items With The Maximum Sum

Choose exactly kk items from a bag containing $1, \0,and, and -1$ values to maximize the total sum.

Acceptance 0%
Problem Statement

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, and numNegOnes.
  • An integer k specifies how many items must be chosen.
  • The available multiset contains:
    • numOnes items of value 1
    • numZeros items of value 0
    • numNegOnes items of value -1

Output Format

  • Return a single integer: the maximum sum achievable by selecting exactly k items.

Constraints

  • 0 <= numOnes, numZeros, numNegOnes <= $10^{5}$
  • 0 <= k <= numOnes + numZeros + numNegOnes
  • Exactly k items must be selected.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.