1588. Sum of All Odd Length Subarrays
作者:互联网
Given an array consisting of n
integers, find the contiguous subarray of given length k
that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
- 1 <=
k
<=n
<= 30,000. - Elements of the given array will be in the range [-10,000, 10,000].
class Solution { public int sumOddLengthSubarrays(int[] arr) { int res = 0; int n = arr.length; int size = n % 2 + n / 2; for(int i = 0; i < size; i++) { int cursize = i * 2 + 1; int cursum = 0; for(int j = 0; j < n; j++) { if(j < cursize) { cursum += arr[j]; } else { cursum = cursum - arr[j - cursize] + arr[j]; } if(j >= cursize - 1) res += cursum; } } return res; } }
1,3, 5,7,9的sliding window sum,注意index要 ≥ cursize - 1时window才准备好了,这时才可以加到res中。
ref:643 https://leetcode.com/problems/maximum-average-subarray-i/
标签:1588,res,int,Subarrays,average,arr,cursize,cursum,Odd 来源: https://www.cnblogs.com/wentiliangkaihua/p/13760060.html