Maximum Average Subarray



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)) } }