Skip to content

2679. Sum in a Matrix 👍

  • Time: $O(n \texttt{sort}(\texttt{row}))$
  • Space: $O(\texttt{sort}(\texttt{row}))$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int matrixSum(vector<vector<int>>& nums) {
    int ans = 0;

    for (vector<int>& row : nums)
      ranges::sort(row);

    for (int j = 0; j < nums[0].size(); ++j) {
      int mx = 0;
      for (int i = 0; i < nums.size(); ++i)
        mx = max(mx, nums[i][j]);
      ans += mx;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int matrixSum(int[][] nums) {
    int ans = 0;

    for (int[] row : nums)
      Arrays.sort(row);

    for (int j = 0; j < nums[0].length; ++j) {
      int mx = 0;
      for (int i = 0; i < nums.length; ++i)
        mx = Math.max(mx, nums[i][j]);
      ans += mx;
    }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def matrixSum(self, nums: list[list[int]]) -> int:
    for row in nums:
      row.sort()

    return sum(max(col) for col in zip(*nums))