4

I have given a an array A of n integer , and Q query in the form of X D for each query i have to find the maximum element in sub array [Ax , A(x-D),A(x-2D)..]

For example:

A = [1,2,3,4,5,6,17,8]
we have query 7 2
Sub Array [17,5,3,1] Ans=17

How can we solve this with a time complexity better than O(Q*N) since no index is updated , can it be solved offline with some technique

I don't think Square Decomposition will work here.

OmG
  • 18,337
  • 10
  • 57
  • 90
Narendra Modi
  • 851
  • 1
  • 13
  • 29
  • Is `O(sqrt N)` per query good enough? If not, what makes you think that it won't work? – kraskevich Nov 24 '16 at 16:57
  • What (in this context) is a `Segment Tree`, and what is the connection to the problem presented in this question? If `Q` is a query, what is the `Q` in `O(Q*N)`? – greybeard Nov 27 '16 at 21:34

1 Answers1

1

Let D greater than sqrt(N). Then the sequence x, x - d, x - 2 * d, ... contains at most sqrt(N) elements. Thus, a naive solution works in O(sqrt(N)) per query in this case.

Let D <= sqrt(N). There are at most sqrt(N) such distinct D's. Let's iterate over them. For a fixed value d, we can compute f[i] = max(a[i], f[i - d]) for all i in linear time (boundary conditions need to be handled properly). The the answer for all queries (X, D), where D = d, is just f[X].

The total time complexity is O((N + Q) * sqrt(N)). This solution uses a linear amount of space.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
  • While doing `sqrt decomposition` all the elements with a block are not necessary to be include in a subarray for a query , so how keep the count maximum element in a block , since maximum element within a block changes based on the value of `D` – DreamWorks Nov 24 '16 at 19:51
  • @DreamWorks The array is not split into blocks. Queries are (based on the value of their `D`). – kraskevich Nov 24 '16 at 19:53
  • Can you provide a sudo code , it will be more clear – DreamWorks Nov 24 '16 at 19:54