DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

Maximum Average Subarray I | LeetCode | Java

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[i-k];
            res = Math.max(res, sum/k);
        }

        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)