Sponsored
Sponsored
The sliding window technique allows us to keep track of the sum of a subarray of fixed length k by adding one new element and removing the first element of the previous window, thus achieving O(n) time complexity.
Time Complexity: O(n)
Space Complexity: O(1)
1class Solution {
2 public double findMaxAverage(int[] nums, int k) {
3 int sum = 0;
4 for (int i = 0; i < k; i++) {
5 sum += nums[i];
6 }
7 int maxSum = sum;
8 for (int i = k; i < nums.length; i++) {
9 sum = sum - nums[i - k] + nums[i];
10 maxSum = Math.max(maxSum, sum);
11 }
12 return (double) maxSum / k;
13 }
14 public static void main(String[] args) {
15 Solution sol = new Solution();
16 int[] nums = {1, 12, -5, -6, 50, 3};
17 int k = 4;
18 System.out.println(sol.findMaxAverage(nums, k));
19 }
20}
In Java, a similar sliding window approach is used. We maintain a running sum of the first k elements. As we slide the window across the array, we adjust the sum by subtracting the element going out of the window and adding the new element. We keep track of the maximum sum encountered.
The brute force approach involves checking every possible subarray of length k and calculating its average, then keeping track of the maximum average found. However, this approach is not efficient for large inputs.
Time Complexity: O(n*k)
Space Complexity: O(1)
1function
The JavaScript brute force solution focuses on iterating through each possible subarray of k length, calculating the average, and identifying the maximum average value. It iteratively sums up values for each subarray but can be slow for large arrays due to the double loop structure.