Problem Description
Given an m x n matrix, create a new matrix "answer" which is initially identical to the input matrix. Then, for each cell in "answer" that contains a -1, replace that value with the maximum value found in its corresponding column in the original matrix. The guarantee is that every column contains at least one non-negative integer.
Key Insights
- We need to compute the maximum for each column in the matrix.
- After computing the column maximums, traverse the matrix again.
- If an element is -1, replace it with the precomputed maximum for that column.
- Given the constraints (matrix dimensions up to 50x50), a simple two-pass solution is efficient.
Space and Time Complexity
Time Complexity: O(m * n) – one pass to compute maximums and another pass to update the matrix. Space Complexity: O(n) – additional array to store the maximum element for each of the n columns.
Solution
The solution involves two major steps:
- Compute the maximum value for each column by iterating over all rows for each column.
- Use an auxiliary list (or array) "colMax" of size n to store the maximum values.
- Create a copy of the original matrix called "answer" and iterate over it.
- For each element that is equal to -1, replace it with the corresponding column maximum from "colMax". This approach uses basic array operations without any advanced data structures, ensuring clarity and efficiency.