Improved Brute Force Algorithm