LeetCode 2679: Sum in a Matrix Solution
Master LeetCode problem 2679 (Sum in a Matrix), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2679. Sum in a Matrix
Problem Explanation
Explanation
To solve this problem, we need to iterate over each row in the matrix, find the maximum value in that row, remove it, and keep track of the maximum value found so far. We continue this process until all elements are removed from the matrix. The sum of all the maximum values found will be our final score.
Algorithm:
- Initialize a variable
scoreto 0. - While the matrix is not empty:
- Iterate over each row and find the maximum value in that row.
- Remove the maximum value from each row.
- Update the
scoreby adding the maximum value found.
- Return the
score.
Time Complexity:
The time complexity of this algorithm is O(n * m), where n is the number of rows and m is the number of columns in the matrix.
Space Complexity:
The space complexity of this algorithm is O(1) as we are not using any extra space apart from a few variables.
Solution Code
class Solution {
public int matrixScore(int[][] nums) {
int score = 0;
while (nums.length > 0) {
int maxVal = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int rowMax = Arrays.stream(nums[i]).max().getAsInt();
maxVal = Math.max(maxVal, rowMax);
nums[i] = Arrays.stream(nums[i]).filter(num -> num != rowMax).toArray();
if (nums[i].length == 0) {
nums = ArrayUtils.remove(nums, i);
i--;
}
}
score += maxVal;
}
return score;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2679 (Sum in a Matrix)?
This page provides optimized solutions for LeetCode problem 2679 (Sum in a Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2679 (Sum in a Matrix)?
The time complexity for LeetCode 2679 (Sum in a Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2679 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2679 in Java, C++, or Python.