原题链接在这里:http://www.lintcode.com/zh-cn/problem/sliding-window-matrix-maximum/

题目:

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 number inside the window at each moving.
Return 0 if the answer does not exist.

For matrix

[
[1, 5, 3],
[3, 2, 1],
[4, 1, 9],
]

The moving window size k = 2
return 13.

At first the window is at the start of the array 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.

题解:

用sum matrix来表示以[i,j]为右下角点时整个左上方的matrix的和. sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1].

需要减掉sum[i-1][j-1]因为加重复了.

然后每次算以[i][j]为右下角, 边长为k的小matrix的和, sum[i][j] - sum[i-k][j] - sum[i][j-k] + sum[i-k][j-k].

需要加上sum[i-k][j-k]因为减重复了.

Time Complexity: O(m*n), m = matrix.length, n = matrix[0].length.

Space: O(m*n).

AC Java:

 public class Solution {
public int maxSlidingMatrix(int[][] matrix, int k) {
if(matrix == null || matrix.length < k || matrix[0].length < k){
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int [][] sum = new int[m+1][n+1];
for(int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
}
} int res = Integer.MIN_VALUE;
for(int i = k; i<=m; i++){
for(int j = k; j<=n; j++){
res = Math.max(res, sum[i][j]-sum[i-k][j]-sum[i][j-k]+sum[i-k][j-k]);
}
}
return res;
}
}
05-21 12:32