Maximum Average Subarray I

Published by

on

Problem

https://leetcode.com/problems/maximum-average-subarray-i/description

Solution

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        double result = Integer.MIN_VALUE;
        int right = 0;
        int sum = 0;
        for (right=0;right<k;right++) {
            sum += nums[right];
        }
        // System.out.println("sum: " +sum);
        result = Math.max(result, (double) sum / k);
        
        for(right=k;right<nums.length;right++) {
            sum+=nums[right];
            sum-=nums[right-k];
            result = Math.max(result, (double) sum / k);
        }
        return result;
    }
}

Notes

  • Sliding window 의 fixed window size의 대표적인 문제
  • (double) 형 변환에 주의

Leave a comment

Previous Post
Next Post