LeetCode solutions

2715. K Items With the Maximum Sum

My accepted Python solution to LeetCode problem 2715, K Items With the Maximum Sum, running in 4ms.

  • Difficulty: Easy
  • Python
  • Runtime 4ms
  • Memory 17.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 4ms, memory 17.2MB, accepted 2026-01-01.

python
class Solution:
    def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:
        # Take as many 1s as possible
        ones_taken = min(numOnes, k)
        k -= ones_taken
        
        # Take 0s if needed (doesn't affect sum)
        zeros_taken = min(numZeros, k)
        k -= zeros_taken
        
        # Take -1s if still need more items
        neg_ones_taken = k  # remaining k must be -1s
        
        return ones_taken - neg_ones_taken

Source