Minimum Average of K Consecutive
Given an array of integers and a window size k, find the minimum average value among all subarrays of length k. Return the minimum average as a floating-point number.
For example, in [3, 1, 5, 2, 4] with k=3, windows: [3,1,5] avg=3.0, [1,5,2] avg=2.67, [5,2,4] avg=3.67. Minimum average is 2.67. With k=2: [3,1] avg=2.0, [1,5] avg=3.0, [5,2] avg=3.5, [2,4] avg=3.0. Minimum is 2.0.
Finding the minimum average is a sliding window optimization problem. It is used in time series analysis (lowest moving average), stock trading (lowest average price over a period), and signal processing (minimum smoothing).
The solution uses a sliding window to maintain the sum incrementally, computes the average after each slide, and tracks the minimum average seen.
Edge cases include k larger than the array (return 0), an empty array (return 0), and negative values (the minimum average may be negative).
Example Input & Output
Algorithm Flow
Solution Approach
Use a sliding window to maintain the sum incrementally and track the minimum average.
Sum the first window and compute its average. Slide the window, updating the sum, computing each new average, and tracking the minimum. Return the minimum average found.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public double solution(int[] nums, int k) {
if (nums == null || nums.length == 0 || k <= 0) return 0.0;
int n = nums.length;
double sum = 0.0;
for (int i = 0; i < k; i++) sum += nums[i];
double minAvg = sum / k;
for (int i = k; i < n; i++) {
sum += nums[i] - nums[i - k];
minAvg = Math.min(minAvg, sum / k);
}
return minAvg;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
