I used bubble sort and because it is O(n^2) complexity, it gave me a timeout the first time and the second time, it accepted my solution. But it's supposed to be faster with merge sort.

My question is, this looks like a dynamic programming problem. But I don't know how to implement it. Has anyone got any idea? Thanks in advance.