Optimizing a leetcode-style question - DP/DFS
The task is the following:
- Given N heights, find the minimum number of suboptimal jumps required to go from start to end. [1-D Array]
- A jump is suboptimal, if the height of the starting point i is less or equal to the height of the target point j.
- A jump is possible, if j-i >= k, where k is the maximal jump distance.
- For the first subtask, there is only one k value.
- For the second subtask, there are two k values; output the amount of suboptimal jumps for each k value.
- For the third subtask, there are 100 k values; output the amount of suboptimal jumps for each k value.
My Attempt
The following snippet is my shot at solving the problem, it gives the correct solution.
This was optimized to handle multiple k values without having to do a lot of unnecessary work. The Problem is that even a solution with a single k value is o(n^2) in the worst case. (As k <= N) A solution would be to eliminate the nested for loop, this is what I'm uncertain about how to approach it.
def solve(testcase):
N, Q = 10, 1
h = [1 , 2 , 4 ,2 , 8, 1, 2, 4, 8, 16] # output 3
# ^---- + ---^ 0 ^--- + --^ + ^
k = [3]
l_k = max(k)
distances = [99999999999] * N
distances[N-1] = 0
db = [ [0]*N for i in range(N)]
for i in range(N-2, -1, -1):
minLocalDistance = 99999999999
for j in range(min(i+l_k, N-1), i, -1):
minLocalDistance = min(minLocalDistance, distances[j] + (h[i] <= h[j]))
db[i][j] = distances[j] + (h[i] <= h[j])
distances[i] = minLocalDistance
print(f"Case #{testcase}: {distances[0]}")
NOTE: This is different from the classic min. jumps problem