DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

2 1 1

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more