Problem: Integers have friends.

After seeing the tutorial of this problem, I learnt about the sparse table. The tutorial though provides the method which is sparse table construction and then using binary search, I could not completely understand it. The comment section was pretty helpful but now the older comment section has been deleted. Can someone please explain what they have done( preferably an approach using sparse table because I have spent a lot of time learning it.)

If possible, please explain it in a beginner-friendly manner as I have never used a sparse table till now. It would really be helpful to me...

Part 1 (Why GCD?):

Firstly, let's find the answer for a fixed array (not subarray). How can we do that? Let's use the fact that $$$(x + m * y) \mod m = x \mod m$$$ for every $$$x$$$, $$$y$$$ and $$$m$$$. Every difference of two numbers must be divisible by $$$m$$$ because $$$y$$$ must be an integer. What's the biggest number that divides every $$$a_i$$$? It's just their GCD! $$$m$$$ can't be equals to $$$1$$$ according to the statement, so now the problem is to find the longest subarray with GCD > 1.

Part 2 (Solving for every subarray efficiently):

Let's build GCD sparse table on differences of $$$a$$$. If you're familiar with two pointers technique (if not, there's a very nice lesson in EDU!), you will easily come up with such solution:

Let's maintain two pointers — $$$L = 0$$$ and $$$R = 0$$$.

While $$$R < n$$$:

2.1. While $$$GCDQuery(L, R) = 1$$$ increase L by 1.

Corner case: $$$a_i = 1$$$. Stop the movement of $$$L$$$ pointer when $$$L = R$$$.2.2. If $$$GCDQuery(L, R) > 1$$$, then do $$$ans = max(ans, R - L + 2)$$$. Why am I using $$$R - L + 2$$$ instead of $$$R - L + 1$$$? That's because the number of differences in $$$a$$$ equals to $$$n - 1$$$.

Implementation:

CodeThanks bro. This is really cool...:)