LeetCode solutions

3764. Maximum Sum With at Most K Elements

My accepted Python solution to LeetCode problem 3764, Maximum Sum With at Most K Elements, running in 139ms.

  • Difficulty: Medium
  • Python
  • Runtime 139ms
  • Memory 43.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 139ms, memory 43.6MB, accepted 2025-12-30.

python
class Solution:
    def maxSum(self, grid: List[List[int]], limits: List[int], k: int) -> int:
        # For each row, get the top limits[i] elements
        candidates = []
        for i, row in enumerate(grid):
            # Sort row in descending order and take top limits[i] elements
            sorted_row = sorted(row, reverse=True)
            candidates.extend(sorted_row[:limits[i]])
        
        # Sort all candidates in descending order and take top k
        candidates.sort(reverse=True)
        return sum(candidates[:k])

Source