Optimal Paths To Target
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:
Example Problem:
Given a m x n grid filled with non-negative 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:
Solution:
Problem 1: Minimum Cost Tickets
In a country popular for train travel, you have planned some train traveling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold for costs[1] dollars;
a 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Solution:
Optimizations and things to note:
For days we don't travel, dp[i] = dp[i-1]
To look up whether we travel on a day or not, we can store all the days in a set for easy lookup
Last updated
Was this helpful?