LeetCode 75
Maximum Average Subarray I
- Problem
- LC 643
- Topic
- Sliding Window
- File
- official75_LC643MaximumAverageSubarrayI.java
- Path
- pkg5leetcode/official75/official75_LC643MaximumAverageSubarrayI.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC643MaximumAverageSubarrayI.java
- Approach
- Fixed-size sliding window sum of length k.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Maximum Average Subarray I | LC 6435 * APPROACH: Fixed-size sliding window sum of length k.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC643MaximumAverageSubarrayI {9 static double findMaxAverage(int[] nums, int k) {10 int sum = 0;11 for (int i = 0; i < k; i++) sum += nums[i];12 int best = sum;13 for (int i = k; i < nums.length; i++) {14 sum += nums[i] - nums[i - k];15 best = Math.max(best, sum);16 }17 return (double) best / k;18 }19 20 public static void main(String[] args) {21 check(Math.abs(findMaxAverage(new int[]{1,12,-5,-6,50,3}, 4) - 12.75) < 1e-9, "case1");22 check(Math.abs(findMaxAverage(new int[]{5}, 1) - 5.0) < 1e-9, "case2");23 System.out.println("all tests passed");24 }25 26 static void check(boolean cond, String name) {27 if (!cond) throw new AssertionError("FAILED: " + name);28 System.out.println(" PASS " + name);29 }30}