Optimal Path To Target
A Dynamic Programming Approach

Algorithms and Data Structures: TheAlgorist.com

System Design: DistributedComputing.dev

Low Level Design: LowLevelDesign.io

Frontend Engineering: FrontendEngineering.io
The DP problems belonging to this category, in its simplest form, looks like below or some kind of variations of it:
 Given a target find minimum (maximum) cost / path / sum to reach the target.
The solution for this kind of problems, in a very generalized form, would often look like below:

Choose optimal (minimal or maximal, as the case may be) path among all possible paths
that lead to the current state, and then add value for the current state.

routes[curr] = min(routes[curr  1], routes[curr  2], ... , routes[curr  k]) + cost[i]
where current target can be reached only from (curr  1), (curr  2), ... (curr  k).

Overall the solution would look like this :
for (int curr = 1; curr <= target; curr++) { for (int k = 0; k < waysToReachCurrentTarget.size(); k++) { dp[i] = min(dp[curr], dp[waysToReachCurrentTarget[k]] + cost / path ) ; } } return dp[target];
The below problem and its solution beautifully demonstrate this approach:
Problem Statement:
Given a m x n grid filled with nonnegative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[ [1,3,1], [1,5,1], [4,2,1] ]Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
Naive Solution:
This is a Premium Content.
Please subscribe to Algorithms course to access the solution.
Optimized Solution:
This is a Premium Content.
Please subscribe to Algorithms course to access the solution.
Problem Solving:
Instructor:
If you have any feedback, please use this form: https://thealgorists.com/Feedback.