Input: L[] = {1, 4, 3, 1}, R[] = {15, 8, 5, 4}
Output: 4
Input: L[] = {1, 5, 9, 13, 21}, R[] = {15, 8, 12, 20, 30}
Output: 5
Explanation: Numbers having maximum occurrence i.e 2 are
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. The smallest number among all are 5.
The idea is to use the Difference array technique. Create a vector initialized with value zero. Iterate through every range and mark the presence of the beginning of every range by incrementing the start of the range with one i.e. arr[L[i]]++ and mark the end of the range by decrementing at index one greater than the end of range by one i.e. arr[R[i]+1]--.
Now when computing the prefix sum, Since the beginning is marked with one, all the values after beginning will be incremented by one. Now as increment is only targeted only till the end of the range, the decrement on index R[i]+1 prevents that for every range i.
L[] = {1, 2, 3} , R[] = {3, 5 , 7}
1. For beginning of range arr[L[i]]++ the array becomes {0,1,1,1,0,0,0,0,......}
2. For end of range arr[R[i]+1]-- the array becomes {0,1,1,1,-1, 0, -1, 0,-1,......}
3. After prefix sum the array becomes {0,1,2,3,2,2,1,1,0...}
Do prefix sum, the sum of elements after (1) is incremented by one because beginning was marked. Now elements after (3) must not be incremented so if there's a range one, two, three, the values from one, two, three should only be incremented by one or their frequency should be incremented by one.
That is why decreasing the value of arr[R[i]+1] is needed so that elements after the end of this range have minus one subtracted to values. That is how to nullify the impact of incrementing the value when prefix will be taken.
So when taking the prefix, simply decrement every value after the range ends, since I want to increment elements only in the range. That's the idea of this algorithm.