2500. Delete Greatest Value in Each Row

Difficulty:
Related Topics:
Similar Questions:

Problem

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

Perform the following operation until grid becomes empty:

Note that the number of columns decreases by one after each operation.

Return the answer after performing the operations described above.

  Example 1:

Input: grid = [[1,2,4],[3,3,1]]
Output: 8
Explanation: The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.

Example 2:

Input: grid = [[10]]
Output: 10
Explanation: The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.

  Constraints:

Solution (Java)

class Solution {
    public int deleteGreatestValue(int[][] grid) {
        boolean[][] picked = new boolean[grid.length][grid[0].length];
        int result = 0;
        while(!check(picked)) {
            int maxValue = Integer.MIN_VALUE;
            for (int row = 0; row < grid.length; row++) {
                int maxValueForRow = Integer.MIN_VALUE;
                int maxColIndexForRow = 0; 
                for (int col = 0; col < grid[0].length; col++) {
                    if (picked[row][col]) {
                        continue;
                    }
                    if (grid[row][col] >= maxValueForRow) {
                        maxValueForRow = grid[row][col];
                        maxColIndexForRow = col;
                    }
                }
                picked[row][maxColIndexForRow] = true; 
                maxValue = Math.max(maxValue, maxValueForRow);
            }
            result = result + maxValue;
        }
        return result;
    }    
    public boolean check(boolean[][] picked) {
        for (int i = 0; i < picked.length; i++) {
            for (int j = 0; j < picked[0].length; j++) {
                if (!picked[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }
}

Explain:

nope.

Complexity: