[LeetCode] Sum in a Matrix

2679. Sum in a Matrix

You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty:

  1. 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.
  2. Identify the highest number amongst all those removed in step 1. Add that number to your score.

Return the final score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int matrixSum(vector<vector<int>>& nums) {
for(auto& n : nums) sort(begin(n), end(n));
int res = 0, len = 0;
for(int i = 0; i < nums.size(); i++) len = max(len, (int)nums[i].size());
for(int i = 0; i < len; i++) {
int ma = 0;
for(int j = 0; j < nums.size(); j++) {
if(nums[j].size() > i) ma = max(ma, nums[j][i]);
}
res += ma;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/13/PS/LeetCode/sum-in-a-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.