File: k-items-with-the-maximum-sum/solution.py

Date: 2026-06-06

Time: 17:10

K Items With the Maximum Sum

Purpose

This file solves LeetCode 2600. It implements a greedy strategy for picking k items from three bags — one containing 1s, one containing 0s, one containing -1s — to maximize the total sum. It's a pure algorithmic module with no dependencies; its single function is imported by k-items-with-the-maximum-sum/test_solution.py.

Key Components

max_sum(numOnes, numZeros, numNegOnes, k) -> int — The sole exported function. It computes the maximum sum achievable by greedily taking items in value order: all available 1s first, then 0s, then -1s.

The implementation is a closed-form expression rather than a loop:


return min(k, numOnes) - max(0, k - numOnes - numZeros)

Breaking this apart:

The sum equals (count of 1s picked) × 1 + (count of 0s picked) × 0 + (count of -1s picked) × (-1), which simplifies to exactly the expression above.

Patterns

Dependencies

Flow

1. Caller passes counts of each item type and the pick budget k.

2. The function computes how many 1s are picked (min(k, numOnes)), which is the positive contribution.

3. It computes how many -1s are forced (max(0, k - numOnes - numZeros)), which is the negative contribution.

4. Returns the difference — no mutation, no side effects.

Invariants

Error Handling

None. The function has no error paths — no exceptions, no validation, no edge-case guards. It relies entirely on the caller (and LeetCode's problem constraints) to provide valid inputs.

Topics to Explore

Beliefs