Found optimal algorithm from first try.