add py3 soln max subarray
This commit is contained in:
parent
7129351ed4
commit
56e8fc22e6
22
0643_maximum-average-subarray-i/README.md
Normal file
22
0643_maximum-average-subarray-i/README.md
Normal 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`
|
25
0643_maximum-average-subarray-i/python3/solution.py
Normal file
25
0643_maximum-average-subarray-i/python3/solution.py
Normal 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
|
Loading…
Reference in New Issue
Block a user