Bloomberg interview question

A slight variation of leetcode 252