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:

  • numOnes items with 1s written on them.
  • numZeros items with 0s written on them.
  • numNegOnes items 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
K Items With the Maximum Sum INPUT BAG CONTENTS 1 1 1 0 0 x3 x2 numOnes = 3 numZeros = 2 numNegOnes = 0 k = 4 Pick 4 items total ALGORITHM STEPS 1 Pick 1s first Take min(k, numOnes) picked = min(4,3) = 3 2 Update remaining k = k - picked k = 4 - 3 = 1 3 Pick 0s next Take min(k, numZeros) picked = min(1,2) = 1 4 Calculate sum sum = ones - negatives sum = 3*1 + 1*0 = 3 Selected Items: 1 1 1 0 (k=4) FINAL RESULT Maximum Sum 3 Calculation: 3 ones --> 3 x 1 = 3 1 zero --> 1 x 0 = 0 0 negs --> 0 x -1 = 0 Total = 3 + 0 + 0 = 3 OK Greedy picks maximize the total sum Key Insight: Greedy approach: Always pick items with value 1 first to maximize sum, then pick 0s (no change), and only pick -1s if absolutely necessary. Order: 1s --> 0s --> -1s. Time: O(1), Space: O(1) TutorialsPoint - K Items With the Maximum Sum | Greedy Strategy
Asked in
Amazon 15 Microsoft 12 Google 8
12.5K Views
Medium Frequency
~5 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen