FastPrepMinimum Cost to Serve Requests on a Ring

Minimum Cost to Serve Requests on a Ring

MathWorks logoMathWorks● MediumFULLTIMEOA

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[]) → long

Examples

Example 1

cost = [1,2,3,4]requests = [3,2,4]return = 9

You start at element 1.

  • 1 -> 3: going 1 -> 2 -> 3 leaves elements 1 and 2 and costs 1 + 2 = 3. Going 1 -> 4 -> 3 costs 1 + 4 = 5. Take 3.
  • 3 -> 2: going 3 -> 2 costs 3. Going 3 -> 4 -> 1 -> 2 costs 3 + 4 + 1 = 8. Take 3.
  • 2 -> 4: going 2 -> 3 -> 4 costs 2 + 3 = 5. Going 2 -> 1 -> 4 costs 2 + 1 = 3. Take 3.

The total is 3 + 3 + 3 = 9.

Example 2

cost = [5,1,1]requests = [1,2,2]return = 5

The 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 = 3

Going 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, where n == cost.length
  • 1 <= cost[i] <= 10^6
  • 1 <= requests.length <= 10^5
  • 1 <= requests[j] <= n

More MathWorks problems

See MathWorks hiring insights
Saved
public long minimumRingCost(int[] cost, int[] requests) {
    // Write your solution here.
}
Checking account…