Codility - TapeEquilibrium

https://codility.com/programmers/task/tape_equilibrium

My solution

def solution(a)
  first_sum = a[0]
  second_sum = a[1..-1].reduce(0, :+)
  min_diff = (first_sum - second_sum).abs

  a.each_index do |p|
    next if p == 0
    next if p == a.length - 1

    first_sum = first_sum + a[p]
    second_sum = second_sum - a[p]
    diff = (first_sum - second_sum).abs
    min_diff = diff if diff < min_diff
  end

  min_diff
end

Learning points

Comments

comments powered by Disqus