Found these questions to be pretty tough. Brute force solution wasn't acceptable as you can judge by constraints.