Problem
You are given a 0-indexed 2D integer array nums
. Initially, your score is 0
. Perform the following operations until the matrix becomes empty:
- 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.
- Identify the highest number amongst all those removed in step 1. Add that number to your score.
Return the finalscore.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 300
1 <= nums[i].length <= 500
0 <= nums[i][j] <= 10^3
Solution
Method 1 – Sort Each Row and Simulate
Intuition
If we sort each row in ascending order, the largest numbers in each row will always be at the end. In each round, we remove the largest remaining number from each row, and the score for that round is the maximum among those numbers. Repeat until all columns are removed.
Approach
- Sort each row in ascending order.
- For each column from the last to the first:
- Collect the largest remaining number from each row (i.e., the last element in each row).
- The score for this round is the maximum of these numbers.
- Add this score to the total.
- Return the total score.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n log n)
— Each row is sorted, and then each column is processed in O(m) time. - 🧺 Space complexity:
O(1)
— Sorting is in-place, and only a few variables are used.