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 in Each Row INPUT grid (3x3 matrix) 1 2 1 3 4 5 6 7 2 Input Values: grid = [[1,2,1], [3,4,5],[6,7,2]] ALGORITHM STEPS 1 Sort Each Row Sort rows in ascending order 1 1 2 3 4 5 2 6 7 2 Process Columns Take max from each column 3 Column Operations Col 0: max(1,3,2) = 3 Col 1: max(1,4,6) = 6 Col 2: max(2,5,7) = 7 4 Sum Maximums 3 + 6 + 7 = 16 FINAL RESULT Operations Summary: Operation 1: Delete max each row max(2,5,7) = 7 Operation 2: Delete max each row max(1,4,6) = 6 Operation 3: Delete max each row max(1,3,2) = 3 Total Sum: 7 + 6 + 3 = 16 OUTPUT 16 OK Key Insight: Sorting each row simplifies finding the greatest value. After sorting, the last column contains the largest values, second-last contains second largest, etc. Taking column-wise maximum after sorting is equivalent to the original operation. Time: O(m*n*log(n)), Space: O(1). TutorialsPoint - Delete Greatest Value in Each Row | Optimal Solution
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