This is one of the primary optimized problem for most ACM/ICPC or OI participants.
From O(n^3) to O(n^2), you will see how stupid you are.