Sum in a Matrix Problem
#2679
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2679.
You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty:
- From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen.
- Identify the highest number amongst all those removed in step 1. Add that number to your score.
Return the final score.
Example 1:
Input: nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]]
Output: 15
Explanation: In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15.
Example 2:
Input: nums = [[1]]
Output: 1
Explanation: We remove 1 and add it to the answer. We return 1.
Constraints:
1 <= nums.length <= 3001 <= nums[i].length <= 5000 <= nums[i][j] <= 10^3
Solution
Approach: Sort each row
Each round removes the largest remaining number from every row and scores the largest of those. Sorting every row puts the numbers removed in the same round into the same column, so the answer is the sum, over all columns, of the largest value in that column.
Complexity: time O(m * n * log n), space O(log n) for the sort, where the matrix has m rows and n columns.
class Solution:
def matrixSum(self, nums: List[List[int]]) -> int:
for row in nums:
row.sort()
return sum(map(max, zip(*nums)))