given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3 Output: 9Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2 Output: 7Explanation: Subarray with maximum sum is [3, 4].
固定窗口
public static int findMaxSumSubArray(int k, int[] arr) {
if (k <= 0 || arr == null || arr.length == 0){
return -1;
}
int sum = 0;
int result = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (i < k) {
sum += arr[i];
} else {
sum = sum - arr[i - k] + arr[i];
result = Math.max(result,sum);
}
}
return result;
}
近期评论