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.
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
Comments