#2679
Sum in a Matrix
MediumArraySortingHeap (Priority Queue)MatrixSimulationSortingGreedy Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach involves sorting each row in descending order first. This allows us to easily access the maximum elements in each iteration without needing to search for them, leading to a more efficient solution.
⚙️
Algorithm
4 steps- 1Step 1: Sort each row of the matrix in descending order.
- 2Step 2: Initialize a score variable to 0.
- 3Step 3: For each column index, find the maximum element from the first elements of each row and add it to the score.
- 4Step 4: Move to the next column and repeat until all columns are processed.
solution.py10 lines
1# Full working Python code
2class Solution:
3 def getMatrixSum(self, nums):
4 for row in nums:
5 row.sort(reverse=True)
6 score = 0
7 for col in range(len(nums[0])):
8 max_value = max(row[col] for row in nums)
9 score += max_value
10 return scoreℹ
Complexity note: The time complexity is O(n log n) due to the sorting of each row, and the space complexity is O(1) since we are not using any additional data structures that grow with input size.
- 1Sorting each row allows for efficient access to maximum values.
- 2Removing elements can be avoided by simply tracking column indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.