Given n
towers numbered 1, 2, 3,...,n, with their height (h[i] = towers[i]
's height) and a number k.
Two tower a, b are considered friends iff:
- a - b = k
- h[a] == h[b]
- max(h[a+1], h[a+2] ... h[b - 1]) <= h[a]
How many `friendships' are there ?
Solution is straight forward:
for i = 1, 2, 3, 4, 5, ..., n - k:
if h[i] == h[i+k]:
for j in range[i, i+k] :
MAX = max(MAX, h[j]
if MAX <= h[i]:
ans++
But I want the solution in the most efficient way. Please help.
For a large n
, the program will eat the RAM; to reduce that, instead of array I used a queue to add the height of towers (when q.size() == k, Just q.pop() ) . Checking for 3rd condition with a large k with naive solution must take time.