Solution


Approach #1 Brute Force [Time Limit Exceeded]

The simplest method is to create a actual 2-D array of size x(), perform all the operations one by one on the given range of elements, and then count the number of maximum elements. Now, we know that all the operations performed always include the element at index . Thus, the element will always be the maximum. After performing all the operations, we can count the number of elements equal to to get the required count of the maximum elements.

Complexity Analysis

  • Time complexity : . Array is updated times, where represents number of times operation is preformed i.e. .

  • Space complexity : . Array of size is used.


Approach #2 Single Pass [Accepted]

Algorithm

As per the given problem statement, all the operations are performed on a rectangular sub-matrix of the initial all 0's matrix. The upper left corner of each such rectangle is given by the index and the lower right corner for an operation is given by the index .

The maximum element will be the one on which all the operations have been performed. The figure below shows an example of two operations being performed on the initial array.

Range_Addition

From this figure, we can observe that the maximum elements will be the ones which lie in the intersection region of the rectangles representing the operations. Further, we can observe that to count the number of elements lying in this intersection region, we don't actually need to perform the operations, but we need to determine the lower right cornerof the intersecting region only. This corner is given by , where reprsents the minimum value of from among all the 's in the given set of operations.

Thus, the resultant count of elements lying in the intersection is given by: x.

Complexity Analysis

  • Time complexity : . Single traversal of all operations is done. refers to the number of operations.

  • Space complexity : . No extra space is used.


Analysis written by: @vinod23