fix run-time limit bug

reduce running time from n^3 to n^2