If Shelly chooses a range , the amount of Tang he can eat each day is the minimum value of in this range. Instead of finding the optimal range of the days, let’s find the optimal amount of Tang per day. We can find the range where is minimum by maintaining a monotonous stack. So, the naive approach will be: iterate from to and for each , calculate the total amount of Tang he can drink if he treats as the Tang amount each day. The total amount will be = . The maximum of them will be the answer. Now, this approach won’t surely fit in time limit. We need to optimize it.
We can observe that, for each query , we can classify the values in some types:
. For this type, we can precalculate the total amount and perform range maximum query using segment tree or similar type data structures.
. For this type, the amount of Tang Shelly can drink is . The only variable part here is . It is similar to the line equation . So, we can apply CHT (Convex Hull Trick) to find the maximum amount in this case. Our query will be .
. It is similar to type .
. The amount of Tang Shelly can drink is . As the full range is being covered, we can just find the maximum and then multiply it with the necessary term. Range maximum can be found by using a segment tree or similar type data structures.
The problem is how we can apply the proper operation on the proper types efficiently. To do that, we can process the queries offline.
For type , we can iterate from to . When we are on the th index, we will process those that have . We will update the value on the position . After that, we can process those queries that have . We need to perform the max query on the range . As the indexes aren’t processed yet, the already processed are .
For type , we can iterate from to like before. When we are on the th index, we will process those that have . We will update the value on the position . Before that, we need to process those queries that have . We need to perform the max query on the range . As the indexes are processed before the query, the already processed are .
For type , we will iterate from to . When we are on the th index, we will process those that have . We need to maintain such a segment tree that contains a Dynamic CHT on every node. So, when we perform an update on the position , the necessary values will be inserted into the Dynamic CHT of each updatable node. The updatable nodes are the nodes of the ranges in the segment tree that include . But before this update, we must process those queries that have . We need to perform the max query on the range. Since the segment tree has Dynamic CHT on each node, we can answer it easily by performing queries on the CHT when we are on the valid nodes. As the indexes are processed before the query, the already processed are . We can get the values for type in a similar fashion.
After we process all the types, we can easily get our desired answer for each query.
Time complexity: