Dynamic programming in O(N^2)