DP based solution for 350 (runs in 3 mins).