1 package solution37; 2 3 class Solution { 4 public int solution(int n,int[] a) { 5 int[] preSum = new int[n+1]; 6 for(int i=1;i<=n;i++){ 7 preSum[i] = preSum[i-1] + a[i-1]; 8 } 9 //[1,2,3,3,2,1] -> [0,1,3,6,9,11,12] 10 int maxLength = 1; 11 float maxValue = 0; 12 for(int l=1;l<=n;l++){ 13 for(int i=0;i<n;i++){ 14 int end = i+l; 15 if(end > n) { 16 break; 17 } 18 int begin = i; 19 int curSum = preSum[end] - preSum[begin]; 20 float avg = curSum / l; 21 if(avg >=maxValue){ 22 maxValue = avg; 23 maxLength = l; 24 } 25 } 26 } 27 return maxLength; 28 } 29 }
算法思路:数组,计算前序和。
通过前序和数组中两个元素的差,快速计算连续子数组的和,以提高算法执行速度。