Sum in a Matrix Solution in Python


Problem Description

So, you’ve stumbled upon the “Sum in a Matrix” problem on LeetCode, huh? Imagine you’re at a buffet, and you have a plate that can only hold the maximum amount of food from each dish. You go around, scoop the best of the best from each dish, and then you sit down to enjoy your meal. But wait! You realize you need to calculate how much food you’ve actually piled on your plate. That’s pretty much what this problem is about, but instead of food, we’re dealing with numbers in a matrix.

In this problem, you are given a matrix of integers. Your task is to find the sum of the maximum elements from each column after sorting each row in ascending order. Sounds simple, right? Well, it is, unless you’re trying to do it while juggling flaming torches!

Code Solution


class Solution:
    def matrixSum(self, nums: list[list[int]]) -> int:
        for row in nums:
            row.sort()
        return sum(max(col) for col in zip(*nums))
    

Approach

The approach taken in the code is straightforward. First, we sort each row of the matrix in ascending order. This ensures that the maximum values are at the end of each row. Then, we use the zip function to group the elements of each column together. Finally, we find the maximum value from each column and sum them up. Voilà! You have your answer.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(m * n log n), where m is the number of rows and n is the number of columns.
Space Complexity O(1), as we are not using any additional data structures that grow with input size.

Real-World Example

Let’s say you’re organizing a talent show, and you have a matrix where each row represents a different act, and each column represents the scores given by different judges. After sorting the scores for each act, you want to know the highest score each act received from any judge. By summing these maximum scores, you can determine the overall best act of the night. Just like that, you’ve solved the “Sum in a Matrix” problem!

Similar Problems

If you enjoyed this problem, you might also like these: