Delete Greatest Value in Each Row - Problem

You are given an m x n matrix grid consisting of positive integers.

Perform the following operation until grid becomes empty:

  • Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
  • Add the maximum of deleted elements to the answer.

Note: The number of columns decreases by one after each operation.

Return the answer after performing the operations described above.

Input & Output

Example 1 — Basic Matrix
$ Input: grid = [[1,2,1],[3,4,5],[6,7,2]]
Output: 16
💡 Note: Round 1: Remove max from each row: [2,5,7], max=7, add to result. Round 2: Remove max from remaining: [1,4,6], max=6, add to result. Round 3: Remove last elements: [1,3,2], max=3, add to result. Total: 7+6+3=16
Example 2 — Single Row
$ Input: grid = [[1,2,3,4]]
Output: 10
💡 Note: Round 1: max=4, Round 2: max=3, Round 3: max=2, Round 4: max=1. Total: 4+3+2+1=10
Example 3 — Single Column
$ Input: grid = [[7],[3],[1]]
Output: 7
💡 Note: Only one column, so we take the maximum element from it: max([7,3,1]) = 7

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 50
  • 1 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Delete Greatest Value ProcessInput Matrix121345672Round 1: Remove Max from Each Row257Removed: [2, 5, 7] → max = 7Round 2: [1, 4, 6] → max = 6Round 3: [1, 3, 2] → max = 3Final Result167 + 6 + 3 = 16Process: Remove max from each row → Find max of removed → Add to result
Understanding the Visualization
1
Input Matrix
3×3 matrix with positive integers
2
Process Rounds
Each round removes max from each row, adds max of removed to result
3
Final Sum
Sum of maximums from each round
Key Takeaway
🎯 Key Insight: Sort each row in descending order first to make finding maximums O(1) per row
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 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