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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs