add py3 soln max subarray

This commit is contained in:
Sangeeth Sudheer 2022-04-15 05:24:03 +05:30
parent 7129351ed4
commit 56e8fc22e6
2 changed files with 47 additions and 0 deletions

View File

@ -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`

View File

@ -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