LeetCode: Maximum Average Subarray I

Question

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

Solution#1

def find_max_average(nums, k)
  num_sum = []
  (0...nums.size).each do |index|
    if nums[index...index+k].size == k
      num_sum << nums[index...index+k].sum
    end
  end
  num_sum.max.to_f / k
end

Solution#2

def find_max_average(nums, k)
  current_sum = nums[0...k].sum
  max_sum = current_sum

  return max_sum.fdiv(k) if nums.length == k

  (1..nums.length-k).each do |index|
    index
    current_sum = current_sum - nums[index-1] + nums[index+k-1]
    max_sum = current_sum if current_sum > max_sum
  end

  max_sum.fdiv(k)
end