Interview Questions

Google - 2

2016-03-22  本文已影响12人  宋翰要长肉

Question

输入是一个array of numbers,一个size, 输出这个size的一个window (start, end) 所包含数字的和,最大

Algorithm

Complexity

Code

public int findMaxSum(int[] nums, int size) {
    int length = nums.length;
    int maxSum = Integer.MIN_VALUE;
    int tempSum = 0;
    for (int i = 0; i < length; i++) {
        if (i < size) {
            tempSum += nums[i];
            if (i == size - 1) {
                maxSum = tempSum;
            }
        } else {
            tempSum += nums[i] - nums[i - size];
            maxSum = Math.max(maxSum, tempSum);
        }
    }
    return maxSum;
}

Follow Up

2-d array, size => find a 2-d window.

Algorithm

Code

public int findMaxSum(int[][] nums, int size) {
    if (nums == null || nums.length == 0 || nums[0].length == 0) {
        return 0;
    }
    int maxSum = Integer.MIN_VALUE;
    int width = nums[0].length;
    int height = nums.length;
    int[][] sum = new int[height + 1][width + 1];
    for (int i = 1; i <= height; i++) {
        for (int j = 1; j <= width; j++) {
            sum[i][j] = sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1] + nums[i - 1][j - 1];
        }
    }
    for (int i = size; i <= height; i++) {
        for (int j = size; j <= width; j++) {
            int tempSum = sum[i][j] - sum[i][j - size] - sum[i - size][j] + sum[i - size][j - size];
            maxSum= Math.max(tempSum, maxSum);
        }
    }
    return maxSum;   
}
上一篇下一篇

猜你喜欢

热点阅读