Any ideas, how do we solve this question ? I tried recursive approach but ended up with stack overflow.