LeetCode.643 Maximum Average Subarray I

来源:互联网 发布:tiu网络用语什么意思 编辑:程序博客网 时间:2024/06/05 10:59

题目:

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 = 4Output: 12.75Explanation: 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 double findMaxAverage(int[] nums, int k) {        //给定数组,找出连续的子串(其中平均值最大),返回该最大的子串平均值        //思路:使用PreSum求解        int [] preSum=new int[nums.length];        preSum[0]=nums[0];        //求和        for(int i=1;i<nums.length;i++){            preSum[i]=nums[i]+preSum[i-1];        }                //求解        //初始k个元素和        int max=preSum[k-1];        for(int i=k;i<nums.length;i++){            int temp=preSum[i]-preSum[i-k];            max=Math.max(max,temp);        }                return max/1.0/k;    }}