LeetCode 题解工作台
子数组最大平均数 I
给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。 请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。 任何误差小于 10 -5 的答案都将被视为正确答案。 示例 1: 输入: nums = [1,12,-5,-6,50,3], k = 4 输出: 12.75 解释…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 滑动窗口(状态滚动更新)
答案摘要
我们维护一个长度为 的滑动窗口,每次计算窗口内的和 ,取最大的和 作为答案。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。
请你找出平均数最大且 长度为 k 的连续子数组,并输出该最大平均数。
任何误差小于 10-5 的答案都将被视为正确答案。
示例 1:
输入:nums = [1,12,-5,-6,50,3], k = 4 输出:12.75 解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
示例 2:
输入:nums = [5], k = 1 输出:5.00000
提示:
n == nums.length1 <= k <= n <= 105-104 <= nums[i] <= 104
解题思路
方法一:滑动窗口
我们维护一个长度为 的滑动窗口,每次计算窗口内的和 ,取最大的和 作为答案。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
ans = s = sum(nums[:k])
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
ans = max(ans, s)
return ans / k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates should understand how to implement the sliding window technique and avoid brute force solutions.
- question_mark
Look for an understanding of maintaining a running sum efficiently during window shifts.
- question_mark
Candidates who are familiar with space optimization techniques and avoid unnecessary data structures will perform well.
常见陷阱
外企场景- error
Candidates may incorrectly compute the sum after sliding the window, resulting in incorrect averages.
- error
Misunderstanding the sliding window approach could lead to a brute-force solution with O(n*k) complexity.
- error
Candidates might forget to handle small edge cases such as when the array has only one element.
进阶变体
外企场景- arrow_right_alt
Consider using a sliding window for other array problems, like finding the maximum sum of subarrays.
- arrow_right_alt
What if k was dynamic? How would you adjust the sliding window approach to accommodate varying subarray sizes?
- arrow_right_alt
Extend the solution to find the subarray with the maximum product instead of the sum.