본문 바로가기
Problem Solving/LeetCode

[LeetCode] 643. Maximum Average Subarray I - Java

by graycode 2026. 9. 15.

• 문제 링크

 

Maximum Average Subarray I - LeetCode

Can you solve this real interview question? Maximum Average Subarray I - You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return thi

leetcode.com

 

• 풀이 코드

public class Solution {

    public double findMaxAverage(int[] nums, int k) {
        int sum = 0;
        for (int i = 0; i < k; i++) sum += nums[i];

        int max = sum;
        for (int i = k; i < nums.length; i++) max = Math.max(max, sum += nums[i] - nums[i - k]);

        return (double) max / k;
    }

}

댓글