You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty:

1. 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.

2. Identify the highest number amongst all those removed in step 1. Add that number to your score.

Return the final score.

Input & Output

Example 1 — Basic Matrix
$ Input: nums = [[7,9,8,6,2],[6,1],[1]]
Output: 25
💡 Note: Round 1: Remove max from each row [9,6,1], score += max(9,6,1) = 9. Round 2: Remove [8,1], score += max(8,1) = 8, total = 17. Round 3: Remove [7], score += 7, total = 24. Round 4: Remove [6], score += 6, total = 30. Round 5: Remove [2], score += 2, total = 32.
Example 2 — Single Row
$ Input: nums = [[1]]
Output: 1
💡 Note: Only one element in the matrix. Remove 1, add to score. Final score = 1.
Example 3 — Multiple Equal Elements
$ Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: 6
💡 Note: Round 1: Remove [3,3,3], max=3, score=3. Round 2: Remove [2,2,2], max=2, score=5. Round 3: Remove [1,1,1], max=1, score=6. Total = 6.

Constraints

  • 1 ≤ nums.length ≤ 50
  • 1 ≤ nums[i].length ≤ 50
  • 1 ≤ nums[i][j] ≤ 103

Visualization

Tap to expand
Sum in a Matrix - Visual Explanation INPUT 2D Integer Array: nums Row 0: 7 9 8 6 2 Row 1: 6 1 Row 2: 1 Blue = max in each row After Sorting (desc): Row 0: [9,8,7,6,2] Row 1: [6,1] Row 2: [1] Initial score = 0 score = 0 ALGORITHM STEPS 1 Sort Each Row Sort descending order 2 Iterate by Columns Process column by column 3 Find Column Max Get max from each column 4 Add to Score Accumulate the max value Iteration Details: Col Values Max Score 0 9,6,1 9 9 1 8,1 8 17 2 7 7 24 3 6 6 30 *Col 4,5: only row 0 remains FINAL RESULT Score Calculation: Column 0: max(9,6,1) = 9 Column 1: max(8,1) = 8 Column 2: max(7) = 7 Column 3: max(6) = 6 Column 4: max(2) = 2 (Row 0 only remains) Total: 9+8+7+6+2-7 = Final Score: 25 OK - Verified! Key Insight: Sort each row in descending order. Then, iterate column by column (left to right). For each column, find the maximum value among all rows that have elements at that index. Time Complexity: O(m * n log n) where m = rows, n = max columns. Space: O(1) extra. TutorialsPoint - Sum in a Matrix | Optimal Solution
Asked in
Amazon 15 Microsoft 12 Google 8
12.5K Views
Medium Frequency
~15 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen