zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    Java泛型 E、T、K、V、N
    二维码生成,二维码中嵌套图片,文字生成图片
    线程之线程安全解决
    多线程的卖票示例来理解两种创建线程方法的区别
    多线程
    Object类
    Runtime
    9.Lambda表达式入门
    匿名内部类
    局部内部类
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13760060.html
Copyright © 2011-2022 走看看