Problem Β· Dynamic Programming
Factory Cost Part 2 β Three Stages with Transit
Learn this problemProblem statement
A product must pass through exactly three production stages in order. For each stage, choose exactly one factory.
stages[i] lists the factories available at stage i. Each factory is [position, productionCost], where position is its coordinate on a one-dimensional line.
The total cost is the sum of the three selected production costs plus the transit costs between consecutive selected factories. Moving between positions x and y costs |x-y|. There is no inbound cost before stage 0 and no outbound cost after stage 2.
Return the minimum possible total cost.
Practice sequence
- Part 1: ignore positions and minimize production cost.
- Part 2: exactly three stages with transit cost (current).
- Part 3: arbitrary number of stages.
Function
findMinimumCostThreeStages(stages: int[][][]) β longExamples
Example 1
stages = [[[20,100],[0,50],[1,30]], [[10,100],[2,20],[56,10]], [[10,10],[1,12],[3,5]]]return = 57Choose [1,30], [2,20], and [3,5]. Production costs total 55 and transit costs total |1-2| + |2-3| = 2, for 57. Checking all combinations shows this is the minimum.
Example 2
stages = [[[0,10]], [[5,1],[1,8]], [[2,4]]]return = 23Choosing stage-1 factory [1,8] costs 10 + 8 + 4 in production and |0-1| + |1-2| = 2 in transit, total 24; choosing [5,1] costs 10 + 1 + 4 + 5 + 3 = 23.
Constraints
stages.length == 3.- Every stage contains at least one factory.
- Each factory is
[position, productionCost]. - Positions and production costs are integers; production costs are non-negative.
- Return the result as a signed 64-bit integer.