A repair enzyme is bound to a DNA strand and scans it looking for damage.
The strand is divided into n consecutive positions, numbered from 0 to n-1, and binding to position i costs the enzyme cost[i] units of energy (some regions are tightly packed and harder to bind).
The enzyme starts bound to position 0 and must end bound to position n-1.
At each move it can:
- slide to the next position (
i → i+1), or - hop over one position (
i → i+2).
The enzyme pays the cost of every position it binds to, including the first and the last one.
Problem Description
Given a list of integers cost, where cost[i] is the energy needed to bind to position i, compute the minimum total energy the enzyme needs to go from position 0 to position n-1.
Example
Input
[3, 1, 4, 1, 5]
Output
10
Explanation
The cheapest route is 0 → 1 → 3 → 4:
3 + 1 + 1 + 5 = 10
Any other route is more expensive, e.g. 0 → 2 → 4 costs 3 + 4 + 5 = 12.
Function Description
Implement the following function:
def minSlidingEnergy(cost: list[int]) -> int:
# Write your code hereParameters
cost: list ofn ≥ 1non-negative integers,cost[i]is the energy needed to bind to positioni
Returns
int: minimum total energy to go from position0to positionn-1
💡 Hint
Let best(i) be the minimum energy needed to be bound to position i.
The enzyme arrived at position i either from position i-1 (slide) or from position i-2 (hop):
What are the base cases best(0) and best(1)? (Remember that the enzyme always starts at position 0.)
Then fill a 1D table from left to right, so that every value is computed only once:
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| cost | 3 | 1 | 4 | 1 | 5 |
| best(i) | 3 | 4 | 7 | ? | ? |
What is the time and space complexity of your solution?
Test
Input2
[2, 7, 1, 8, 2, 8, 1, 8]
Output2
14