leetcode 643 Maximum Average Subarray I

題目詳情

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.

輸入一個數組nums和一個整數k。要求找出輸入數組中長度爲k的子數組,而且要求子數組元素的加和平均值最大。返回這個最大的平均值。數組

Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: 最大平均值 (12-5-6+50)/4 = 51/4 = 12.75code

思路

  • 創建一個長度爲k的滑動窗口(即一個長度爲k的子數組),而後每次右移一位,並將當前的平均值和存儲的最大平均值比較,保留更大的那個值便可。

解法

public double findMaxAverage(int[] nums, int k) {
        double curr = 0;
        double max = 0;       
        
        for(int i=0;i<nums.length;i++){
            if(i < k){
                curr = curr + nums[i];
                max = curr;
                continue;
            }
            curr = curr + nums[i] - nums[i-k];    
            max = (curr > max) ? curr : max ;
            
        }
        
        
        return max/k;
        
    }
相關文章
相關標籤/搜索