LeetCode 643. Maximum Average Subarray I
原题链接在这里:https://leetcode.com/problems/maximum-average-subarray-i/description/
题目:
Given an array consisting of n
integers, find the contiguous subarray of given length k
that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
- 1 <=
k
<=n
<= 30,000. - Elements of the given array will be in the range [-10,000, 10,000].
题解:
维护长度为k的sliding window的最大sum.
Note: In Java, Double.MIN_VALUE is the smallest positive double value, thus here use -Double.MAX_VALUE.
Time Complexity: O(nums.length). Space: O(1).
AC Java:
1 class Solution { 2 public double findMaxAverage(int[] nums, int k) { 3 double res = -Double.MAX_VALUE; 4 double sum = 0; 5 for(int i = 0; i < nums.length; i++){ 6 sum += nums[i]; 7 if(i >= k - 1){ 8 res = Math.max(res, sum / k); 9 sum -= nums[i - k + 1]; 10 } 11 } 12 13 return res; 14 } 15 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步