Approach
This is actually a beginner friendly version of Sliding Window algorithm. Because we will run a loop from 0 till K, calculate the sum. From K we will start eliminating and adding elements at the same time.
Try to learn this using pen and paper.
Code
public double findMaxAverage(int[] nums, int k) {
double res = 0;
double sum = 0;
for(int i=0; i<k; i++){
sum += nums[i];
}
res = sum/k;
int n = nums.length;
for(int i=k; i<n; i++){
sum = sum + nums[i] – nums[i–k];
res = Math.max(res, sum/k);
}
return res;
}
}
Thanks for reading🥰.
Feel free to comment🖌️ and like the post💓
Follow for more 🤝 && Happy Coding🚀👩💻
Don’t forget to check-out my other socials😍:
Github
Hashnode
Medium
Twitter(X)