So, I just got hacked on this problem from the recent Div4 contest for problem G1 and I still don't know why. I got TLE but there is nothing in my code that could've caused it. Can someone please help?
Submission Link: https://codeforces.net/contest/1791/submission/192492521 Problem Link: https://codeforces.net/contest/1791/problem/G1
Array.sort() in java has worst case time complexity of O(n^2), that's why your code gave tle.
My google search tells me Arrays.sort() has a time complexity of O(nlogn)
Have a look here.
cause you use java
Instead of using array and Arrays.sort() , use ArrayList and Collections.sort().
I've been hacked twice due to this :(
192512576 <--- You can check out this, i've just modified your code.
I just use an array of Integer instead of int. Since it’s an object instead of an primitive type, Arrays.sort becomes nlogn with merge.
Be careful when using == with object data types, you have to use .equals.
You should use C++ even Java uses C++ !
sometine Python uses C++ too
In Java, calling
Arrays.sort()
on an array of primitives uses the quicksort algorithm (hence it is possible to create adversarial cases that exhibit $$$\mathcal{O}(n^2)$$$ behavior) -- note the same is not true for arrays of reference types.To remedy this, one solution is to first randomly shuffle your array before sorting it, or to use a different sorting algorithm (
Collections.sort()
for example).