Skip to main content
Back to problems
#2600
Easy Algorithms

K items with the maximum sum

Math Greedy
60.2% acceptance
Feb 25, 2026
336
40
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. numZeroes 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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn k_items_with_maximum_sum(num_ones: i32, num_zeros: i32, num_neg_ones: i32, k: i32) -> i32 {
    // Greedily pick: 1s first, then 0s, then -1s.
    let _ = num_neg_ones; // may be needed if k exceeds ones+zeros
    let take_ones = num_ones.min(k);
    let remaining = k - take_ones;
    let take_zeros = num_zeros.min(remaining);
    let take_neg = remaining - take_zeros;
    take_ones - take_neg
  }
}