I'm doing a ruby problem and my solution works. However, it does not work on bigger test cases because it takes too long to process.
The method takes two inputs, an array of numbers and a number.
The goal is to find the first two numbers in the array whose sum is the number provided in the input.
The first pair means that the highest index of the pair is lower than the highest index of any other pairs in the array that add to the number.
Example - ([10, 5, 2, 3, 7, 5], 10)
The answer should be [3, 7] while [5, 5] also sums to 10, the index of the last 5 is 5 and the index of 7 is 4, so [3, 7] comes first.
def sum_pairs(ints, s)
return nil if ints.empty? || ints.nil?
x = ints.combination(2).select {|x, y| x + y == s}
return nil if x.nil? || x.empty?
ints.rindex(x[0][1]) > ints.rindex(x[-1][1]) ? x.last : x.first
end
My code worked for all test cases besides those with large arrays.
I was wondering if there was a built in method to help or if I needed to loop through the array differently.
sum_pairs([5, 5, 4, 6, 5], 10)returns[4, 6]