Problem Description
Given a 2D integer matrix called nums, you repeatedly perform the following operations until the matrix becomes empty:
- From each row that is not empty, remove the largest number.
- Of all removed numbers in that round, take the highest one and add it to your overall score. Return the final score after all operations.
Key Insights
- Each row's largest remaining element is chosen at each round.
- Sorting rows enables direct access to the largest elements without repeatedly scanning.
- After sorting, the i-th round removes the i-th largest element of each row (if available).
- The maximum among these removed elements is added to the score in each round.
- Simulation is done by iterating through the sorted rows column-by-column from the end.
Space and Time Complexity
Time Complexity: O(n * m * log(m)) where n is the number of rows and m is the average number of columns; sorting each row dominates. Space Complexity: O(n * m) for storing the matrix, with additional space negligible.
Solution
We first sort each row in non-decreasing order. This step ensures that the largest elements are positioned at the end of every row. Then, rather than "simulating" removals dynamically, we iterate over possible rounds. In round i, for every row that has at least i elements, we consider its i-th largest element (i.e., element at index row_length - i). We compute the maximum of these elements across all rows and add this value to the overall score. This approach avoids costly repeated removals and efficiently computes the required score.