changed K from constant to half of min(N,M)