Skip to content

Instantly share code, notes, and snippets.

@CarlosLCervantes
Created March 1, 2018 02:42
Show Gist options
  • Save CarlosLCervantes/88b364828901343dc3f6205d6395896e to your computer and use it in GitHub Desktop.
Save CarlosLCervantes/88b364828901343dc3f6205d6395896e to your computer and use it in GitHub Desktop.
Evaluate if array has sum equal to max value
def has_sum_with_max_val(arr)
raise "Invalid Input Array" if arr.nil? || arr.length < 3
raise "Contains Invalid Value" if arr.any? { |n| !n.is_a? Numeric || n < 0 }
has_max_sum = false
arr.sort! { |a, b| b <=> a }
max_num = arr.shift
arr.each_with_index do |num, i|
total = num
(i + 1).upto(arr.length - 1) do |j|
new_total = total + arr[j]
if new_total > max_num
next
else
total = new_total
end
if total == max_num
has_max_sum = true
break
end
end
end
has_max_sum
end
puts has_sum_with_max_val [1,2,5,7,10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment