"100DaysOfCode: LeetCode Problem #643 - Maximum Average Subarray I"

🚀 Day 29 of #100DaysOfCode – LeetCode Problem #643: Maximum Average Subarray I 🧩 Problem: Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average value. 💡 Approach: This problem is a great example of the Sliding Window Technique 🪟 Calculate the sum of the first k elements. Then slide the window by one element at a time — subtract the element that goes out, add the new one coming in. Keep track of the maximum sum seen. Return the maximum average (maxSum / k). 💻 Java Code: class Solution { public double findMaxAverage(int[] nums, int k) { double sum = 0; for (int i = 0; i < k; i++) { sum += nums[i]; } double max = sum; for (int i = k; i < nums.length; i++) { sum += nums[i] - nums[i - k]; max = Math.max(max, sum); } return max / k; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This one reinforces how sliding window optimizations can drastically simplify what looks like a brute-force problem!

To view or add a comment, sign in

Explore content categories