How to find three consecutive numbers with the largest sum in an array of integers in Ruby

1 Answer

0 votes
# find_max_sum_of_three finds 'k' consecutive numbers with the largest sum in an array.
# It returns an array containing the maximum sum and the matching sub-array.
def find_max_sum_of_three(numbers, k)
  # Validate input parameters: k must be positive and array length must be at least k
  return nil if k <= 0 || numbers.length < k

  # each_cons(k) generates sliding windows of size k, 
  # and max_by(&:sum) finds the window with the highest total sum.
  max_window = numbers.each_cons(k).max_by(&:sum)
  max_sum = max_window.sum

  [max_sum, max_window]
end

# Example usage:
numbers = [4, 2, 0, 8, 7, 5, 1, 3, 9, 6]
k = 3

sum, result = find_max_sum_of_three(numbers, k)

if sum
  puts "Largest sum: #{sum}"
  puts "Numbers: #{result.join(' ')}"
else
  puts "Invalid parameters or array too short."
end


# run:
# 
# Largest sum: 20
# Numbers: 8 7 5
#

 



answered Oct 30 by avibootz

Related questions

...