I am making out the problem to be in context of discrete optimization... using brute force to avoid the problem in best possible way... let's do it...