Sure! Below is the Python version of your provided C++ code. This code computes the maximum sum of a submatrix within a 2D list v such that the sum is less than or equal to a given integer k. If no such submatrix exists, it returns -1.
def max_submatrix_sum(v, k):
if not v or not v[0]:
return -1
n = len(v)
m = len(v[0])
# Initialize the prefix sum matrix
ps = [[0] * m for _ in range(n)]
# Compute the first column of the prefix sum matrix
for i in range(n):
ps[i][0] = v[i][0]
# Compute the first row of the prefix sum matrix
for j in range(m):
ps[0][j] = v[0][j]
# Compute the rest of the prefix sum matrix
for i in range(1, n):
for j in range(1, m):
ps[i][j] = ps[i - 1][j] + ps[i][j - 1] - ps[i - 1][j - 1] + v[i][j]
max_sum = float('-inf')
# Iterate over all possible submatrices
for sx in range(n):
for sy in range(m):
for ex in range(sx, n):
for ey in range(sy, m):
# Calculate the sum of the current submatrix using the prefix sum matrix
current_sum = ps[ex][ey]
if sx > 0:
current_sum -= ps[sx - 1][ey]
if sy > 0:
current_sum -= ps[ex][sy - 1]
if sx > 0 and sy > 0:
current_sum += ps[sx - 1][sy - 1]
# Update max_sum if the current_sum is within the limit
if current_sum <= k:
max_sum = max(max_sum, current_sum)
return -1 if max_sum == float('-inf') else max_sum
Explanation
-
Prefix Sum Matrix (ps) Construction:
- First Column and First Row: The first column and first row of the prefix sum matrix are initialized directly from the input matrix
v.
- Rest of the Matrix: Each cell
ps[i][j] is computed by adding the value from the cell above (ps[i-1][j]), the value from the cell to the left (ps[i][j-1]), subtracting the overlapping top-left cell (ps[i-1][j-1]), and then adding the current value v[i][j].
-
Finding the Maximum Submatrix Sum ≤ k:
- The code iterates over all possible submatrices defined by their top-left corner
(sx, sy) and bottom-right corner (ex, ey).
- For each submatrix, it calculates the sum using the prefix sum matrix to do so efficiently.
- If the calculated sum is less than or equal to
k, it updates max_sum if this sum is greater than the current max_sum.
-
Final Result:
- After checking all possible submatrices, if
max_sum remains -inf, it means no valid submatrix was found, and the function returns -1.
- Otherwise, it returns the
max_sum found.
Example Usage
# Example matrix
v = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
result = max_submatrix_sum(v, k)
print(result) # Output: 2
In this example, the submatrix [[1, 0], [0, -2]] has a sum of -1, and the submatrix [[0, 1], [-2, 3]] has a sum of 2, which is the maximum sum that does not exceed k=2.
Notes
- Time Complexity: The above implementation has a time complexity of O(n^2 * m^2), which can be slow for large matrices. If you're dealing with larger inputs, you might want to look into more optimized algorithms, such as using binary search with cumulative sums for better performance.
- Edge Cases: Make sure to handle edge cases where the input matrix is empty or
k is very small.
Feel free to adjust the function as needed based on your specific requirements!