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 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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值