Sunday, August 9, 2020

LeetCode [644] Maximum Average Subarray II

644. Maximum Average Subarray II
Hard

Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to 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:
when length is 5, maximum average value is 10.8,
when length is 6, maximum average value is 9.16667.
Thus return 12.75.

Note:

  1. 1 <= k <= n <= 10,000.
  2. Elements of the given array will be in range [-10,000, 10,000].
  3. The answer with the calculation error less than 10-5 will be accepted.
class Solution {
    int n;
    final double E = 0.000001;
    public double findMaxAverage(int[] nums, int k) {
        this.n = nums.length;
        double l = Double.MAX_VALUE, r = l*-1;
        for(int v : nums){
            l = Math.min(l, v);
            r = Math.max(r, v);
        }

        while(Math.abs(r-l)>E){
            double m = l + (r-l)/2;
            if(valid(nums, m, k)){
                l = m;
            }else{
                r = m;
            }
        }
        return l;
    }

    boolean valid(int[] nums, double x, int k){
        double[] pn = new double[n];
        double cur = 0, prv = 0;
        for(int i=0; i<n; ++i){
            pn[i] = nums[i] - x;
            cur += pn[i];

            if(i>=k){
                prv += pn[i-k];
                if(prv<0){
                    cur -= prv;
                    prv = 0;
                }
            }

            if(i+1>=k && cur>=0)
                return true;
        }
        return false;
    }
}

No comments:

Post a Comment