[LeetCode] Delete Greatest Value in Each Row

2500. Delete Greatest Value in Each Row

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

Perform the following operation until grid becomes empty:

  • Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
  • Add the maximum of deleted elements to the answer.

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

Return the answer after performing the operations described above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int deleteGreatestValue(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
for(int i = 0; i < n; i++) sort(begin(A[i]), end(A[i]));
int res = 0;
for(int i = 0; i < m; i++) {
int now = 0;
for(int j = 0; j < n; j++) {
now = max(now,A[j][i]);
}
res += now;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/delete-greatest-value-in-each-row/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.