reworked beta to be 100% successful on Codility. Complexity
time O(n) space O(n)