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 [9,6,1], max=9, score=9. Round 2: Remove [8,1], max=8, score=17. Round 3: Remove [7], max=7, score=24. Round 4: Remove [6], max=6, score=30. Wait, let me recalculate: After removing 9,6,1 we have [[7,8,6,2],[1],[]]. Max is 8, score=17. Continue until matrix empty.
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: 12
💡 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 = 3+2+1 = 6.

Constraints

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

Visualization

Tap to expand
Sum in a Matrix: Complete ProcessInput Matrix:798611Round 1:Extract: [9, 6, 1]Maximum: 9Score: 0 + 9 = 9Remaining:781Round 2:Extract: [8, 1]Maximum: 8Score: 9 + 8 = 17Remaining:7Continue...Round 3: Extract [7], Max: 7, Score: 24Round 4: Extract [6], Max: 6, Score: 30Round 5: Extract [2], Max: 2, Score: 32Final Score25
Understanding the Visualization
1
Input Matrix
2D matrix with different row sizes
2
Extract Maximums
Find and remove largest from each row
3
Calculate Score
Sum the maximum of extracted elements
Key Takeaway
🎯 Key Insight: Sort rows first to avoid repeated maximum searches, then process systematically.
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