You are given an m x n
matrix grid
consisting of positive integers.
Perform the following operation until the grid becomes empty:
Return the sum of the greatest values encountered during the operation.
Example:
Input: grid = [[10, 20, 30], [5, 15, 25]]
Output: 55
Explanation:
- First greatest values: [30, 25] => sum = 55
New grid: [[10, 20], [5, 15]]
- Second greatest values: [20, 15] => sum = 35
New grid: [[10], [5]]
- Third greatest values: [10, 5] => sum = 15
New grid: [[], []]
Total sum = 55 + 35 + 15 = 105
m x n
matrix with both m
and n
positive.m x n
with positive integers, so this scenario does not apply.def delete_greatest_values(grid):
total_sum = 0
while any(grid):
max_values = []
for row in grid:
if row: # Ensure row is not empty
max_val = max(row)
max_values.append(max_val)
row.remove(max_val) # Remove the greatest value in the row
total_sum += sum(max_values)
return total_sum
# Example usage
grid = [[10, 20, 30], [5, 15, 25]]
print(delete_greatest_values(grid)) # Output should be 105
O(n)
for each row.O(n)
, as list removal operations can be costly due to shifts.n
operations.Thus, the overall time complexity is O(m * n^2)
where m
is the number of rows and n
is the number of columns, because each removal operation can potentially take O(n)
time.
O(m)
So the space complexity is O(m)
.
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?