
Let ‘N’ be: 2
Let queries be: [[1, 2], [1, 1]]
Let ‘K’ be: 1
Initial heights: [0, 0]
Removing query 1 and increasing heights in the range [1, 1] gives: [1, 0]. The number of candles having a height of 1 is 1.
Removing query 2 and increasing heights in the range [1, 2] gives: [1, 1]. The number of candles having a height of 1 is 2.
Hence, the answer is 2.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains three space-separated integers, ‘N’, ‘K’, and ‘Q’, representing the number of candles, the height of the candle needed, and the number of queries.
The next ‘Q’ lines of each test contain two space-separated integers, ‘L’ and ‘R’, representing the range for each query.
For each test case, print a single integer representing the maximum count of the candle possible after performing ‘Q’ - 1 queries.
Print output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6
1 <= Q <= 10^6
1 <= K <= Q
1 <= L <= R <= N
Time Limit: 1 sec
The basic idea is to run ‘Q’ - 1 queries by removing 1 query at a time. For each time, we find the number of candles with height equal to ‘K’ and find the maximum.
Here is the algorithm :
The basic idea is to make a difference array that can update heights in constant time and calculate the final heights of the candles in linear time. We create an array (say, ‘DIFF’) that will store the updated heights. We take all the queries and update the ‘DIFF’ array by incrementing index ‘L’ by 1 and decreasing index ‘R’ + 1 by 1. We then take the prefix sum of the ‘DIFF’ array to get the final heights of the candles after performing all ‘Q’ queries. As we take the prefix sum, this is the reason we need to decrease index ‘R’ + 1 by 1. Let us understand that by an example.
Let ‘N’ be 4. Initial heights: [0, 0, 0, 0]
Let the queries be: [1, 2], [2, 3]
We update index 1st by +1 and 3rd index by -1. Updated ‘DIFF’ array: [1, 0, -1, 0].
We update the index 2nd by +1 and the 4th index by -1. Updated ‘DIFF’ array: [1, 1, -1, -1].
‘DIFF’ array after updating by prefix sum: [1, 2, 1, 0].
Now we find the count of candles having heights ‘K’ by removing 1 query at a time. How do we find candles having height ‘K’ after removing a range [L, R].
Count of candles having height ‘K’ will be: Candles having height ‘K’ from 0 to ‘L’ - 1 + Candles having height ‘K’ + 1 from ‘L’ to ‘R’ + Candles having height ‘K’ from ‘R’ + 1 to ‘N’.
To find we can use prefix sum which stores candles having height ‘K’ and another prefix array which stores candles having height ‘K’ + 1.
Here is the algorithm :