CF BUDDY
← Problems·

1254B2 · Send Boxes to Alice (Hard Version)

2100 · constructive algorithms, greedy, math

Problem: This is the harder version of the problem. In this version, 1n1061 \le n \le 10^6 and 0ai1060 \leq a_i \leq 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare nn boxes of chocolate, numbered from 11 to nn. Initially, the ii-th box contains aia_i chocolate pieces.

Since Bob is a typical nice guy, he will not send Alice nn empty boxes. In other words, at least one of a1,a2,,ana_1, a_2, \ldots, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k>1k > 1 such that the number of pieces in each box is divisible by kk. Note that Alice won't mind if there exists some empty boxes.

Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box ii and put it into either box i1i-1 or box i+1i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

Input Format: The first line contains a single integer nn (1n1061 \le n \le 10^6) — the number of chocolate boxes.

The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (0ai1060 \le a_i \le 10^6) — the number of chocolate pieces in the ii-th box.

It is guaranteed that at least one of a1,a2,,ana_1, a_2, \ldots, a_n is positive.

Output Format: If there is no way for Charlie to make Alice happy, print 1-1.

Otherwise, print a single integer xx — the minimum number of seconds for Charlie to help Bob make Alice happy.

Note: In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by 1717.

In the second example, Charlie can move a piece from box 22 to box 33 and a piece from box 44 to box 55. Each box will be divisible by 33.

In the third example, each box is already divisible by 55.

In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy.

Sample Cases

Case 1

Input

3
4 8 5

Output

9

Case 2

Input

5
3 10 2 1 5

Output

2

Case 3

Input

4
0 5 15 10

Output

0

Case 4

Input

1
1

Output

-1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback