saptarshikuar2003's blog

By saptarshikuar2003, history, 19 months ago, In English

lets say we have an array a of length n.

we are given q queries with indices l,r.

we have to locate the position of minimum or maximum value within that range....of l,r.

the constraints are
.........1<=n<=10^5 .........1<=l<=r<=n .........1<=ai<=10^9 .........1<=q<=10^5

  • Vote: I like it
  • -5
  • Vote: I do not like it

| Write comment?
»
19 months ago, hide # |
Rev. 3  
Vote: I like it 0 Vote: I do not like it

You can do it by preparing a 2D array x where x[k][i] is the minimum/maximum value in range $$$[i,i+2^k-1]$$$. x[0][i]=a[i] and for each $$$k\geq1$$$, x[k][i]=min(x[k-1][i],x[k-1][i+(1ll<<(k-1)]). The complexity is $$$O(n\log n)$$$, since $$$k\leq\log n$$$, $$$i \lt n$$$ and each x[k][i] can be calculated in $$$O(1)$$$ time.

Then, to calculate the minimum/maximum value of the range $$$[l,r]$$$, calculate the largest number $$$y$$$ such that $$$2^y\leq r-l+1$$$. The answer is min(x[y][l],x[y][r-(1ll<<y)]).

To also find the index of that element, simply use this technique on an array of pairs b[n], where b[i]={a[i],i}.

»
19 months ago, hide # |
 
Vote: I like it +8 Vote: I do not like it

You can do it offline with ordered stack