LeetCode-in-Java

2500. Delete Greatest Value in Each Row

Easy

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.

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.

The final answer = 10.

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    public int deleteGreatestValue(int[][] grid) {
        int sum = 0;
        for (int i = 0; i < grid.length; i++) {
            Arrays.sort(grid[i]);
        }
        for (int j = 0; j < grid[0].length; j++) {
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < grid.length; i++) {
                if (grid[i][j] > max) {
                    max = grid[i][j];
                }
            }
            sum += max;
        }
        return sum;
    }
}