1. 程式人生 > >leetCode-Maximum Average Subarray I

leetCode-Maximum Average Subarray I

2.7 temp dma out integer 表示 script length turn

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 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

My Solution:

class Solution {
    public double findMaxAverage(int[] nums, int k) {
       int max = Integer.MIN_VALUE;
       int len = nums.length;
       int temp = 0;
       if(len == k){
            
for(int num : nums){ temp += num; } return (temp * 1.0)/k; } for(int i = 0;i <= len - k;i++){ temp = 0; for(int j = i;j < i + k;j++){ temp += nums[j]; } if(temp > max){ max
= temp; } } return (max * 1.0) / k; } }

Better Solution1:

//sum[i]存儲的是nums前i+1個元素之和
//sum[i] -sum[i - k]表示以i為最後一個元素,k個元素之和
public class Solution {
    public double findMaxAverage(int[] nums, int k) {
        int[] sum = new int[nums.length];
        sum[0] = nums[0];
        for (int i = 1; i < nums.length; i++)
        sum[i] = sum[i - 1] + nums[i];
        double res = sum[k - 1] * 1.0 / k;
        for (int i = k; i < nums.length; i++) {
            res = Math.max(res, (sum[i] - sum[i - k]) * 1.0 / k);
        }
        return res;
    }
}

Better Solution2:

public class Solution {
//先計算出0開始的前k個元素之和,由於nums[1]+nums[2]...nums[k]= nums[0]+nums[1]+...nums[k - 1]+nums[k] - nums[0],利用這個公式一直以nums[i]為最後一個元素滑動
    public double findMaxAverage(int[] nums, int k) {
        double sum=0;
        for(int i=0;i<k;i++)
            sum+=nums[i];
        double res=sum;
        for(int i=k;i<nums.length;i++){
            sum+=nums[i]-nums[i-k];
                res=Math.max(res,sum);
        }
        return res/k;
    }
}

leetCode-Maximum Average Subarray I