Remove the largest value in each row

You are given a m x nmatrix of size gridconsisting of positive integers.

Do the following until gridbecomes an empty matrix:

  • Remove the element with the largest value from each row. If there are multiple such values, delete any of them.

  • Add the largest value among the removed elements to the answer.

Note that every time an operation is performed, the data in the column of the matrix will be decremented by 1.

Returns the answer after performing the above operations.

Example 1:

img

Input: grid = [[1,2,4],[3,3,1]] 
Output: 8 
Explanation: The figure above shows the values ​​that need to be removed at each step. 
- In the first operation, delete 4 from the first row and 3 from the second row (note that there are two cells with the value 3, we can delete either). Add 4 to the answer. 
- In the second operation, delete 2 from the first row and delete 3 from the second row. Add 3 to the answer. 
- In the third operation, delete 1 from the first row and delete 1 from the second row. Add 1 to the answer. 
Ultimately, the answer = 4 + 3 + 1 = 8.

Example 2:

img

Input: grid = [[10]] 
Output: 10 
Explanation: The figure above shows the values ​​that need to be removed at each step. 
- In the first operation, delete 10 from the first row. Add 10 to the answer. 
Ultimately, the answer = 10.

code show as below:

class Solution {
public:
    int deleteGreatestValue(vector<vector<int>>& grid) {
        int m=grid.size();//定义数组的行数
        int n=grid[0].size();//定义数组的列数
        int sum=0;//存放最终结果
        for(int i=0;i<m;i++)
        {
            sort(grid[i].begin(),grid[i].end());//将每一行中的数字从小到大进行排序	
        }
        for(int i=0;i<n;i++)
        {
            int maxnum=0;定义最大值
            for(int j=0;j<m;j++)
            {
                maxnum=max(maxnum,grid[j][i]);//将每一列中的最大值记录下来
            }
            sum+=maxnum;//将每一列中的最大值进行相加
        }
        return sum;//返回最终结果
        
    }
};

Guess you like

Origin blog.csdn.net/m0_62379712/article/details/131973360