Maximum Average Subarray I | LeetCode | Java

RMAG news

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

class Solution {
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[ik];
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)

Leave a Reply

Your email address will not be published. Required fields are marked *