Maximum Sum Subarray of Size K(最大子数组和为k)
Problem Statement
Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’.
Example
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: Subarray with maximum sum is [3, 4].
solution
public static int findMaxK_Num(int[] a,int k){
if(k==0||a.length==0||a==null){
return 0;
}
int max = Integer.MIN_VALUE;
int sum = 0;
int j = 0;
for(int i=0;i<a.length;i++){
sum +=a[i];
if(i>=k-1){
max = Math.max(max, sum);
sum -=a[j];
j++;
}
}
return max;
}
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)。