본문 바로가기
Data Structure & Algorithms/Arrays and Strings

[Array]643. Maximum Average Subarray I

by 담백로봇 2023. 3. 7.

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

 

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

  • Code template: 3. sliding window
  • Time Complexity: O(n)
  • level: easy
  • Method: Sliding window - fixed window size
  • 숙지할것:
    •  윈도우는 고정되어있기에 그이전 합값을 활용해야한다. 윈도우가 움직이면 맨처음 요소값을 빼고 새로운 요소는 더한다.

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        
        int left = 0, right = k;
        double ans , sum , new_sum ;
        
        for( int i = 0 ; i<right ; i++ ){
            sum+=nums[i];
        }
         
        new_sum = sum;
        ans = sum;
        for( right; right< nums.size(); right ++){
            
            new_sum = new_sum + nums[right]-nums[left]; //이 부분이 핵심이닷
            ans = max(ans,new_sum);
            
            //cout << ans<< "::"<<left << "::" << right << endl;
            left++;    
        }
        
        return ans/k;
        
    }
};

숙지 완료

댓글