196k views
5 votes
There are a number of cities in a row, and there are two bus lines that go between them. They both visit all cities in order, but one may take longer than the other to go between any two cities. Starting on or moving to the Blue line takes a certain amount of extra time. There is no extra time required to start on or move to the Red line. Determine the minimum cost to move from the first city to each of the cities.

Example
red =[2,3,4]
blue =[3,1,1]
blueCost =2

1 Answer

1 vote

Based on the above, the minimum cost to move from the first city to each of the cities is [5, 5, 5].

What is the code for the minimum cost?

Python

def min_cost(red, blue, blue_cost):

n = len(red)

dp = [[float('inf') for _ in range(n)] for _ in range(2)]

dp[0][0] = 0

for i in range(1, n):

dp[0][i] = dp[0][i - 1] + red[i - 1]

dp[1][i] = dp[0][i - 1] + blue[i - 1] + blue_cost

dp[1][i] = min(dp[1][i], dp[1][i - 1] + blue[i - 1])

return dp[1]

red = [2, 3, 4]

blue = [3, 1, 1]

blue_cost = 2

print(min_cost(red, blue, blue_cost))

User Justin Breitfeller
by
8.6k points