Maximum Average Subarray

• A slight performance improvement: avoid division until the return statement. In other words just keep a sliding window of the sum of k elements and return max-sum / k.

• Also the first math.max is not necessary since the test is any number vs the smallest possible number.

• @chris24e Thanks for your suggestion. I have updated the code.

• Same suggestion as chris but for Approach# 2

• the last answer is so good

• Thanks for your suggestion. I have updated the code.

• ?!!? I don't understand the question. why isn't it interpreted as sum the k highest int in the array then divide k?

• easy to understand Java Solution

``````class Solution {
public double findMaxAverage(int[] nums, int k) {

if (nums.length == 1)return (double)nums[0];
double max = Integer.MIN_VALUE;

loop1:
for (int i=0;i<nums.length;i++){
int sum = nums[i];
for (int j=i+1;j<i+k;j++){
if (j>=nums.length)break loop1;
sum = sum + nums[j];
}
double average = (double)sum/k;
if (average>max){
max = average;
}
}
return max;

}
}``````

• Sliding window approach in swift.

``````class Solution {
func findMaxAverage(_ nums: [Int], _ k: Int) -> Double {
if nums.count == 0 {
return 0
}
if nums.count <= k {
return Double(nums.reduce(0, +)) / Double(k)
}
var leftPointer = 0
var rightPointer = k - 1
var runningSum = nums[leftPointer...rightPointer].reduce(0, +)
var maxSum = runningSum
while(rightPointer < nums.count - 1) {
rightPointer += 1
runningSum = runningSum - nums[leftPointer] + nums[rightPointer]
maxSum = max(maxSum, runningSum)
leftPointer += 1
}
return (Double(maxSum) / Double(k))
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.