![]() |
VOOZH | about |
Given an array arr[] of size N where each element denotes a pair in the form (price, weight) denoting the price and weight of each item. Given Q queries of the form [X, Y] denoting the price range. The task is to find the element with the highest weight within a given price range for each query.
Examples:
Input: arr[][] = {{24, 6}, {30, 8}, {21, 7}},
queries[][] = {{10, 24}, {20, 30}}
Output: [7, 8]
Explanation: The following are the items chosen for the above range
For first query: There are two items with given range [10, 24] -> {24, 6} and {21, 7} . Highest weight is 7.
For second query: There are two items with given range [20, 30] -> {24, 6}, {21, 7} and {30, 8}. Highest weight is 8.
Therefore, answer is [7, 8].Input: arr[][] = {{1000, 300}, {1100, 400}, {1300, 200}, {1700, 500}, {2000, 600}},
queries[][] = {{1000, 1400}, {1700, 500}, {2000, 600}}
Output: [400, 500, 600]
Naive Approach: A Simple Solution is to run a loop for the price range and find the maximum weight for each query.
Time Complexity: O(Q*N).
Auxiliary Space: O(1)
Efficient Approach: An efficient approach is to preprocess to store the maximum weight in the price range [i, j] for any i and j. Use Segment Tree for preprocessing and query in moderate time.
Representation of Segment trees
- Leaf Nodes are the weight corresponding to elements of the input array.
- Each internal node represents the maximum weight of all leaves under it.
An array representation of a tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, the right child is at 2*i+2 and the parent is at ⌊(i – 1) / 2⌋.
The solution can be elaborated by dividing the approach into two parts:
Construction of Segment Tree from the given array:
The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.
See the image below to understand the formation of segment tree for given input.
See the following algorithm for better understanding.
// qs --> query start price, qe --> query end price
int RMQ(node, qs, qe)
{
if price range of node is within qs and qe
return value in node
else if price range of node is completely outside qs and qe
return INFINITE
else
return max( RMQ(node's left child, qs, qe), RMQ(node's right child, qs, qe) )
}
Below is the implementation of the above approach.
400 500 600
Time Complexity: O(N log N + Q*log N)
Auxiliary Space: O(N)
Analyzing Time Complexity: Time Complexity for sorting the given input array is O(N * LogN)
Time Complexity for tree construction is O(N). There is a total of 2N-1 nodes, and the value of every node is calculated only once in tree construction.
The time complexity for each query is O(LogN). To query a range maximum, process at most two nodes at every level, and the number of levels is O(LogN).
Related Topic: Segment Tree