Continue learning
Practice related DSA questions in the same topic.
Travel from the top-left to bottom-right grid cell using right or down moves. The total includes both endpoints. Return the smallest path total. Target gives column count.
Travel from the top-left to bottom-right grid cell using right or down moves. The total includes both endpoints. Return the smallest path total. Target gives column count.
def solve(values, target): dp = values.copy() i = 1 while (i < len(dp)): if (i < target): dp[i] = (dp[i] + dp[(i - 1)]) else: if ((i % target) == 0): dp[i] = (dp[i] + dp[(i - target)]) else: dp[i] = (dp[i] + min(dp[(i - target)], dp[(i - 1)])) i = (i + 1) return dp[(len(dp) - 1)]| 1 | 4 • | 1 |
| 2 | 1 | 3 |
The first row can only be reached from the left.
The first row can only be reached from the left.
A courier records the cheapest arrival fare at every junction before moving onward.
Accumulate the cheapest known predecessor at every cell; the first row and column each have only one predecessor.
O(rows × columns) time · O(rows × columns) auxiliary space
Worked example · {"values":[1,4,1,2,1,3],"target":3} ⇒ 7
Edge case 1 · {"values":[-4],"target":1} ⇒ -4
Edge case 2 · {"values":[2,3],"target":1} ⇒ 5
The start cell must be counted exactly once.
How could a second table recover the chosen route?