Ruby 3 Sum O(2)

programming
Tags: #<Tag:0x00007f242074e4b0>

#1
def threeSumClosest(array, target)
     array.sort!

     bestSum = Float::INFINITY

     (0...array.length).each do|i|
          j = i+1
          k = array.length - 1

          while j < k do
               sum  = (array[i] + array[j] + array[k])
               diff = sum - target

               return sum if diff.zero?

               if sum.abs < bestSum.abs
                    bestSum = sum
               elsif sum.abs > target
                    k -= 1
               else
                    j += 1
               end
          end
     end

     bestSum
end