Skip to content

Latest commit

 

History

History
52 lines (42 loc) · 1.23 KB

643. Maximum Average Subarray I.md

File metadata and controls

52 lines (42 loc) · 1.23 KB

leetcode-cn Daily Challenge on Febrary 4th, 2021.


Difficulty : Easy

Related Topics : Array


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

Solution

  • mine
    • Java
      • Runtime: 4 ms, faster than 41.39%, Memory Usage: 98.5 MB, less than 6.41% of Java online submissions
        public double findMaxAverage(int[] nums, int k) {
            int left = 0, right = 0;
            double sum = 0;
            while (right - left < k) {
                sum += nums[right++];
            }
            double ans = sum;
            while (right < nums.length) {
                sum += nums[right++] - nums[left++];
                ans = Math.max(ans, sum);
            }
            return ans / k;
        }