본문 바로가기

Algorithm/LeetCode

643. 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 this value. Any answer with a calculation error less than 10-5 will be accepted.

 

Example 1:

Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

Example 2:

Input: nums = [5], k = 1
Output: 5.00000

 

Constraints:

  • n == nums.length
  • 1 <= k <= n <= 105
  • -104 <= nums[i] <= 104

 

Explanation

val에 이전 Index의 값은 제거하고 다음 인덱스의 값을 넣어주며 k개의 arr의 값을 더한 뒤 k로 나누어 계산하며 저장해둔 값보다 큰 값이면 갱신해나가며 반복해서 해결

 

Time Complexity

O(N)

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        double val = 0;
        double max_val=0;
        for(int i = 0;i<k;i++){
            val += nums[i];
        }
        max_val=val/k;
        for(int i = k;i<nums.length;i++){
            val-=nums[i-k];
            val+=nums[i];
            if(val/k>max_val){
                max_val=val/k;
            }
        }
        return max_val;
    }
}

'Algorithm > LeetCode' 카테고리의 다른 글

1679. Max Number of K-Sum Pairs  (0) 2024.06.17
11. Container With Most Water  (1) 2024.06.15
1732. Find the Highest Altitude  (0) 2024.06.10
2215. Find the Difference of Two Arrays  (0) 2024.06.09