Created
March 1, 2018 02:42
-
-
Save CarlosLCervantes/88b364828901343dc3f6205d6395896e to your computer and use it in GitHub Desktop.
Evaluate if array has sum equal to max value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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