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;
}
};
숙지 완료
'Data Structure & Algorithms > Arrays and Strings' 카테고리의 다른 글
[Array and String] Prefix sum 개념 (1) | 2023.03.09 |
---|---|
[Arrrays and String] 713. Subarray Product Less Than K (투포인트와 슬라이딩 윈도우 개념 헷갈림) (0) | 2023.03.03 |
[arrays and strings] 997.Squares of a Sorted Array (1) | 2023.03.01 |
[Arrays and Strings] 1.Two sum - LeetCode (0) | 2023.02.28 |
[Arrays & String] 2회독 큰그림 잡기 - 자주쓰이는 템플릿정리 (0) | 2023.02.28 |
댓글