What algorithm should i use to solve this or what is the logic behind solving this, an optimal solution, not brute force. I want the idea of how to solve this and maybe the