to make it easy to follow, given 2 buildings,
{(0,4,3), (3,6,4)} as initial data array
there are two ways to proceed,
1. Create a new array like {0,4,3,6} or
2. Create a new array like {(0,3),(3,4),(4,6)}
For 1 sorting can be performed at very last step.
For 2 sorting is needed early and it is a little bit more friendly to SQL operations.
here only focus on way 1
Create a function which take an array and a number and return a new array (to be used as input array for next same function call).
now call the function 4 times in this case,
1st call, input initial data array {(0,4,3), (3,6,4)} and number 0 (first element in list, see way 1 above)
return a new array {(0,4,3), (3,6,4)}
why so? Consider the input number may possibly divid each element into two elements (like one string may divid into 2 substrings depending on the input number). But for input number 0, it is on or outside boundaries for both elements (0,4,3) and (3,6,4) and therefore no split occurs.
2nd call, input the returned array {(0,4,3), (3,6,4)} and number 4 (pick up the 2nd number in list, see way 1 above)
Return a new array {(0,4,3), (3,4,4), (4,6,4)} (because 4 can split the 2nd element (3,6,4) in the input array).
3rd call, input the new returned array {(0,4,3), (3,4,4), (4,6,4)} and number 3 (the 3rd one in list)
return another new array {(0,3,3),(3,4,3), (3,4,4), (4,6,4)} (because only the first element (0,4,3) can be split by input number 3).
4th call, input the returned array from 3rd call {(0,3,3),(3,4,3), (3,4,4), (4,6,4)} and number 6 (the last one in list, see way 1 above).
The last function call returns {(0,3,3),(3,4,3), (3,4,4), (4,6,4)} (should know why by far), which in fact contains everything needed for final answer expression.
Keep in mind, group each distinct range FIRST to take the maximum height in group, eg,
(3,4,3) and (3,4,4) >>> (3,4,4)
this leads to {(0,3,3),(3,4,4),(4,6,4)}
then reconstruct each range with the same height in sequence without gap,
this leads to {(0,3,3),(3,6,4)}
which is the final answer expressed in another way (compare with (0,3),(3,4),(6,0) which means start from x=0 height=3, start from x=3 height=4, and at last point x=6 height=0).
Done!