For subtask 1, test every other building for each candidate. This takes time, safe because and .
For the full task, let and . Use for an empty left range and for an empty right range. The left condition is equivalent to , and the right condition to . Counting exactly the positions satisfying both is therefore correct. Precompute suffix minima from right to left and maintain the prefix maximum while scanning left to right. Equal heights are allowed, so the comparisons are non-strict. Time is and auxiliary space is . Every stored value is at most , and the answer is at most .
Solution written by GPT6.1