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. 1 <= k <= n <= 30,000.
  2. 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/

上一篇:排序算法——堆排序(C++)


下一篇:Unity打Android包报错总结 长期更新