To avoid plagiarism in my university, I am going to modify the problem.
Henry likes to jump from building to building. The heights of each building are given as a list of H numbers. We also number their indices 0,1,…,n−1 from left to right. I want to find out the number of all the buildings that Henry can jump to with these conditions:
Henry can jump from building x to another building y if:
- The building y is not taller than building x
- None of the buildings in between building x and building y are taller than either building x or building y.
For example, if a building x has a height 10, and a building y has a height of 5, and there's a building that has a height of 7 between them, then Henry cannot jump to building y because the building's height in between them is greater than y.
For each building, how many buildings can Henry jump to?
I want it to return as a list.
Here are more examples:
[10, 300, 200] == [0, 2, 0]
Henry cannot jump from building 0 to 1 because 300 > 10. Henry also cannot jump from building 0 to building 2 as building 2 is greater than building 0 and the building in between them is greater than both of them. Henry can jump from building 1 to building 0 and building 2 because building 2 is greater than both of them. Jumping from building 2 to building 1 is not possible as it has a greater height than building 1 and we cannot jump from building 2 to building 0 because the building in between them (building 1) has a height greater than both of them even though building 2 is greater than building 0.
[10000, 1004, 1200] == [2, 0, 1]
[1020, 1020, 1020, 220, 520, 602, 320] == [2, 2, 5, 0, 1, 2, 0]
I've created an O(n^3) solution using two for loops for this solution but it seems highly inefficient. I want to see if there is an O(n log n) solution or an O(n) solution for this one. I am kind of a newbie to programming so something simple could help.
Here is my code:
def valid_jumps(N: list[int]) -> list[int]: validated: list[int] = [] for i in range(len(N)): valid = 0 for j in range(i+1, len(N)): if N[i] >= N[j]: valid += 1 if max(N[i+1:j], default=0) > N[i]: valid -= 1 elif max(N[i+1:j], default=0) > N[j]: valid -= 1 else: break for k in range(i-1, -1, -1): if N[i] >= N[k]: valid += 1 if max(N[k+1:i], default=0) > N[i]: valid -= 1 elif max(N[k+1:i], default=0) > N[k]: valid -= 1 else: break validated.append(valid) return validated
Another edit: Tried to made my post clearer
for; for; max
means O(n^3).\$\endgroup\$max()
implies a third hiddenfor
loop contained in the Python runtime's own code.\$\endgroup\$