Minimum Cost to Serve Requests on a Ring
Problem statement
There are n elements arranged in a ring, numbered 1 through n. Each element is next to the elements before and after it, and elements n and 1 are also next to each other.
You are given an integer array cost of length n. Moving from element i to either of its two neighbors costs cost[i - 1]. The cost of a step depends only on the element you leave, not on the direction you move.
You start at element 1. You are also given an integer array requests. Visit the elements requests[0], requests[1], ... in this order. Between requests you may move clockwise or counterclockwise, one neighbor at a time. A request for the element you are already at costs nothing.
Return the minimum total cost to complete all the requests in order.
Function
minimumRingCost(cost: int[], requests: int[]) → longExamples
Example 1
cost = [1,2,3,4]requests = [3,2,4]return = 9You start at element 1.
1 -> 3: going1 -> 2 -> 3leaves elements 1 and 2 and costs1 + 2 = 3. Going1 -> 4 -> 3costs1 + 4 = 5. Take3.3 -> 2: going3 -> 2costs3. Going3 -> 4 -> 1 -> 2costs3 + 4 + 1 = 8. Take3.2 -> 4: going2 -> 3 -> 4costs2 + 3 = 5. Going2 -> 1 -> 4costs2 + 1 = 3. Take3.
The total is 3 + 3 + 3 = 9.
Example 2
cost = [5,1,1]requests = [1,2,2]return = 5The first request is element 1, where you already are, so it costs nothing. Every route out of element 1 pays cost[0] = 5 first: 1 -> 2 costs 5, and 1 -> 3 -> 2 costs 5 + 1 = 6. The last request is element 2 again and costs nothing. The total is 5.
Example 3
cost = [1,100,1,1,1]requests = [3]return = 3Going 1 -> 2 -> 3 costs 1 + 100 = 101 because it leaves element 2. The longer way 1 -> 5 -> 4 -> 3 costs 1 + 1 + 1 = 3, so the answer is 3.
Constraints
2 <= n <= 2000, wheren == cost.length1 <= cost[i] <= 10^61 <= requests.length <= 10^51 <= requests[j] <= n