diff --git a/0643_maximum-average-subarray-i/README.md b/0643_maximum-average-subarray-i/README.md new file mode 100644 index 0000000..a7fbb27 --- /dev/null +++ b/0643_maximum-average-subarray-i/README.md @@ -0,0 +1,22 @@ +You are given an integer array `nums` consisting of `n` elements, and an integer `k`. + +Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. + +**Example 1:** + + Input: nums = [1,12,-5,-6,50,3], k = 4 + Output: 12.75000 + Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 + + +**Example 2:** + + Input: nums = [5], k = 1 + Output: 5.00000 + + +**Constraints:** + +* `n == nums.length` +* `1 <= k <= n <= 105` +* `-104 <= nums[i] <= 104` \ No newline at end of file diff --git a/0643_maximum-average-subarray-i/python3/solution.py b/0643_maximum-average-subarray-i/python3/solution.py new file mode 100644 index 0000000..ab4b856 --- /dev/null +++ b/0643_maximum-average-subarray-i/python3/solution.py @@ -0,0 +1,25 @@ +# Time: O(N) +# Space: O(1) +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + # Sliding window approach + max_average = float("-inf") + moving_sum = 0.0 + window_start = 0 + + for i in range(0, len(nums)): + moving_sum += nums[i] + + # Need to start computing averages only at this point. + # e.g. Suppose nums = [0, 1, 2, 3] and k = 3 + if i >= k - 1: + # e.g. When i = 3 - 1 = 2, start checking for max average + max_average = max(moving_sum / k, max_average) + + # e.g. Remove element at beginning of window, i.e 0 from [0...2] + moving_sum -= nums[window_start] + + # e.g. Move window position from 0 to 1 + window_start += 1 + + return max_average