Lavishe's blog

By Lavishe, history, 3 months ago, In English

I recently encountered a problem and I am looking for an optimal approach, especially when $$$N$$$ and $$$Q$$$ are large.

The Problem:

Given an array $$$A$$$ of size $$$N$$$ ($$$A_1, A_2, \dots, A_N$$$). The array is circular, meaning $$$A_{N}$$$ is followed by $$$A_1$$$. We have $$$Q$$$ queries. Each query gives an integer $$$L$$$. For each query, we need to find the maximum sum of $$$L$$$ consecutive elements in this circular array.

  • If $$$L \gt N$$$, the segment wraps around the array multiple times.

My Analysis:

Let $$$S$$$ be the sum of all elements in $$$A$$$. For a length $$$L$$$, we can decompose it into full cycles and a remainder:

$$$L = k \cdot N + r$$$

Where $$$k = \lfloor L/N \rfloor$$$ and $$$r = L \pmod N$$$.

The maximum sum for length $$$L$$$ would be:

$$$Ans = k \cdot S + \text{MaxSum}(r)$$$

Where $$$\text{MaxSum}(r)$$$ is the maximum sum of a subarray of length $$$r$$$ in the circular array.

The Constraints & Issue:

  • If $$$N, Q \le 5000$$$, I can precompute $$$\text{MaxSum}(k)$$$ for all $$$k \in [1, N]$$$ in $$$O(N^2)$$$ time using a sliding window on the doubled array, and answer queries in $$$O(1)$$$.

  • However, if $$$N$$$ is up to $$$10^5$$$ and $$$Q$$$ is up to $$$10^5$$$, the $$$O(N^2)$$$ precomputation is too slow (TLE).

My Question:

Is there a known technique to compute $$$\text{MaxSum}(k)$$$ for all $$$k \in [1, N]$$$ faster than $$$O(N^2)$$$? Or is there another approach to handle these queries online without full precomputation in better than $$$O(N)$$$ per query?

Thank you!

  • Vote: I like it
  • +11
  • Vote: I do not like it

»
3 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Lavishe (previous revision, new revision, compare).

»
3 months ago, hide # |
 
Vote: I like it +18 Vote: I do not like it

The MaxSum array is just $$$(max, +)$$$-convolution in disguise, so there are ways to do it better than $$$\Omega(n^2)$$$, but not $$$o(n^{2-\epsilon})$$$ as I know. So, it wouldn't be helpful to you to do these advanced algorithms and still get a TLE, possibly the fastest way might be $$$O(n^2)$$$ with AVX.

»
3 months ago, hide # |
Rev. 2  
Vote: I like it +5 Vote: I do not like it

If you concatenate the array to itself like $$$[1,2,3,4]\to[1,2,3,4,1,2,3,4]$$$ the problem becomes equivalent to finding the maximum of $$$L$$$ consecutive elements in a normal array, which is not possible faster than $$$O(n^2)$$$ as far as I know. But if there is a faster method please enlighten me!