Hackerrank: Bday gift (bug fix and optimization)