LeetCode 2679: Sum in a Matrix
Problem Description
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
score
to 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
score
by 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.
Solutions
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;
}
}
Loading editor...