Given an array of n * m
matrix, and a moving matrix window (size k * k
), move the window from top left to botton right at each iteration, find the maximum sum inside the window at each moving.
Return 0
if the answer does not exist.
Example
Example 1:
Input:[[1,5,3],[3,2,1],[4,1,9]],k=2
Output:13
Explanation:
At first the window is at the start of the matrix like this
[
[|1, 5|, 3],
[|3, 2|, 1],
[4, 1, 9],
]
,get the sum 11;
then the window move one step forward.
[
[1, |5, 3|],
[3, |2, 1|],
[4, 1, 9],
]
,get the sum 11;
then the window move one step forward again.
[
[1, 5, 3],
[|3, 2|, 1],
[|4, 1|, 9],
]
,get the sum 10;
then the window move one step forward again.
[
[1, 5, 3],
[3, |2, 1|],
[4, |1, 9|],
]
,get the sum 13;
SO finally, get the maximum from all the sum which is 13.
Example 2:
Input:[[10],k=1
Output:10
Explanation:
sliding window size is 1*1,and return 10.
Challenge
O(n^2) time.
思路:跟 submatrix sum类似,都是用prefix sum来求最大值;写法跟 submatrix sum一样,用[n+1][m] 的数组来求prefixsum;
核心点在于 t += sum[i][p] - sum[i-k][p], 这里p 属于 [j, j - k + 1]
public class Solution {
/**
* @param matrix: an integer array of n * m matrix
* @param k: An integer
* @return: the maximum number
*/
public int maxSlidingMatrix(int[][] A, int k) {
if(A == null || A.length == 0 || A[0].length == 0 || k <= 0) return 0;
int n = A.length;
int m = A[0].length;
if(n < k || m < k) return 0;
int[][] sum = new int[n+1][m];
int globalmax = Integer.MIN_VALUE;
for(int i = 1; i <= n; i++) {
for(int j = 0; j < m; j++) {
sum[i][j] = sum[i-1][j] + A[i-1][j];
}
if(i < k) continue;
for(int j = 0; j + k - 1 < m; j++) {
int t = 0;
for(int p = j; p <= j + k -1 ; p++){
t += sum[i][p] - sum[i-k][p];
}
globalmax = Math.max(globalmax, t);
}
}
return globalmax;
}
}