Leetcode 2500. Delete Greatest Value in Each Row
You are given an m x n
matrix where each row is sorted in non-decreasing order. You need to delete the greatest value in each row. You repeat this process for the remaining part of the matrix until it becomes empty. The result should be the sum of all the deleted values.
m
and n
?
#include <vector>
#include <iostream>
class Solution {
public:
int deleteGreatestValue(std::vector<std::vector<int>>& grid) {
int totalSum = 0;
while (!grid.empty() && !grid[0].empty()) {
int currentSum = 0;
for (auto& row : grid) {
// Add the greatest value (last element) of the current row
currentSum += row.back();
// Remove the greatest value
row.pop_back();
}
totalSum += currentSum;
}
return totalSum;
}
};
int main() {
Solution solution;
std::vector<std::vector<int>> grid = \{\{1, 3, 5}, {2, 4, 6}};
std::cout << "Sum of deleted values: " << solution.deleteGreatestValue(grid) << std::endl;
return 0;
}
The time complexity of the solution can be analyzed as follows:
n
elements.m
deletions (one for each row).m * n
deletions.So, the time complexity is:
m
is the number of rows and n
is the number of columns.This accounts for traversing each element of the matrix exactly once before it is deleted.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?