_aditya's blog

By _aditya, history, 8 years ago, In English

There is a list of key vs value pair.size = n. No I have been given a key I have to find the max value from the list such that its key is less than the given key.

If there are q queries I can do this in O(qn). Is there a faster way to do this.

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

»
8 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Let each key be an index of the corresponding value. Store the values in a segment tree for maximum. Then, if you need to find the maximum value with key < k you just need to query maximum value on the segment [0;k - 1]. Probably, you may need to compress key values so they would fit the range [0;n].

  • »
    »
    8 years ago, hide # ^ |
    ← Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    If you could answer the queries offline (i.e. you know all the queries before you began to answer them), just sort the queries and key-value pairs by key value and use the fact that the answer for the i - th query in the sorted order is the maximum of the answer of the (i - 1) - th query and all the values having their key between this two queries.

»
8 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

If I am right understood the problem, you should use the Fenwick tree with maximum.