644. Maximum Average Subarray II
Explanation:
The problem asks us to find the maximum average of a subarray with at least k elements within a given array. We can solve this problem using binary search.
Algorithmic Idea:
- We can perform binary search on the maximum average value.
- For each iteration of the binary search, we calculate the difference between each element in the array and the current mid value, and store it in a new array.
- Then, we calculate the prefix sum of the new array.
- Next, we calculate the minimum prefix sum of the subarray with at least k elements.
- If the minimum prefix sum is greater than or equal to zero, it means there exists a subarray with an average greater than or equal to the current mid value. In this case, we update the lower bound of the binary search.
- If the minimum prefix sum is less than zero, it means there doesn't exist a subarray with an average greater than or equal to the current mid value. In this case, we update the upper bound of the binary search.
Time Complexity:
The time complexity of this approach is O(n * log(max - min)), where n is the number of elements in the array, and max and min are the maximum and minimum values in the array.
Space Complexity:
The space complexity of this approach is O(n), where n is the number of elements in the array.
: :
class Solution {
public double findMaxAverage(int[] nums, int k) {
double left = Integer.MAX_VALUE, right = Integer.MIN_VALUE;
for (int num : nums) {
left = Math.min(left, num);
right = Math.max(right, num);
}
double[] diff = new double[nums.length];
while (right - left > 1e-5) {
double mid = (left + right) / 2;
double sum = 0, prev = 0;
boolean check = false;
for (int i = 0; i < nums.length; i++) {
diff[i] = nums[i] - mid;
}
for (int i = 0; i < k; i++) {
sum += diff[i];
}
if (sum >= 0) {
check = true;
}
double minSum = 0;
for (int i = k; i < nums.length; i++) {
sum += diff[i];
prev += diff[i - k];
minSum = Math.min(prev, minSum);
if (sum - minSum >= 0) {
check = true;
break;
}
}
if (check) {
left = mid;
} else {
right = mid;
}
}
return left;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.