Skip to main content
Back to problems
#2679
Medium Algorithms

Sum in a matrix

Array Sorting Heap (Priority Queue) Matrix Simulation
60.4% acceptance
Feb 25, 2026
404
66
You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty: 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. Identify the highest number amongst all those removed in step 1. Add that number to your score. Return the final score.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn matrix_sum(nums: Vec<Vec<i32>>) -> i32 {
    let mut nums = nums;
    for row in &mut nums {
      row.sort_unstable();
    }
    let cols = nums[0].len();
    let mut score = 0;
    for c in (0..cols).rev() {
      let max_val = nums.iter().map(|row| row[c]).max().unwrap_or(0);
      score += max_val;
    }
    score
  }
}