LeetCode 643. Maximum Average Subarray I

原题链接在这里:https://leetcode.com/problems/maximum-average-subarray-i/description/

题目:

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].

题解:

维护长度为k的sliding window的最大sum.

Note: In Java, Double.MIN_VALUE is the smallest positive double value, thus here use -Double.MAX_VALUE.

Time Complexity: O(nums.length). Space: O(1).

AC Java:

复制代码
 1 class Solution {
 2     public double findMaxAverage(int[] nums, int k) {
 3         double res = -Double.MAX_VALUE;
 4         double sum = 0;
 5         for(int i = 0; i < nums.length; i++){
 6             sum += nums[i];
 7             if(i >= k - 1){
 8                 res = Math.max(res, sum / k);
 9                 sum -= nums[i - k + 1];
10             }
11         }
12 
13         return res;
14     }
15 }
复制代码

 

posted @   Dylan_Java_NYC  阅读(182)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示