Problem · Array

Minimum Fuel Car Alignment

Learn this problem
MediumFivetran logoFivetranFULLTIMEPHONE SCREEN

Problem statement

You are given the integer coordinates of n cars in parallel arrays xCoordinates and yCoordinates.

Move every car so that the final positions form one horizontal row with no gaps. You may choose any integer row y, any integer starting position s, and any assignment of cars to the distinct positions (s, y), (s + 1, y), ..., (s + n - 1, y).

Moving a car from (x1, y1) to (x2, y2) costs |x1 - x2| + |y1 - y2| units of fuel.

Return the minimum possible total fuel cost. The result is a 64-bit integer.

Function

minimumFuelCost(xCoordinates: int[], yCoordinates: int[]) → long

Examples

Example 1

xCoordinates = [1,4]yCoordinates = [1,4]return = 5

Choose row y = 1 and final x-coordinates [1, 2]. The cars cost 0 and |4 - 2| + |4 - 1| = 5, for a minimum total of 5.

Example 2

xCoordinates = [0,5,2]yCoordinates = [2,2,2]return = 3

Keep the common row at y = 2 and use x-coordinates [1, 2, 3]. Matching sorted car x-coordinates [0, 2, 5] to them costs 1 + 0 + 2 = 3.

Example 3

xCoordinates = [4,1,3,2]yCoordinates = [3,0,2,1]return = 4

The x-coordinates already occupy four consecutive positions. Choosing y = 1 gives vertical cost 2 + 1 + 1 + 0 = 4.

Constraints

  • 1 <= n <= 2 * 10^5
  • xCoordinates.length == yCoordinates.length == n
  • -10^9 <= xCoordinates[i], yCoordinates[i] <= 10^9
  • Every final coordinate is an integer, and each of the n consecutive final positions is occupied by exactly one car.
  • The minimum total cost fits in a signed 64-bit integer.
drafts saved locally
public long minimumFuelCost(int[] xCoordinates, int[] yCoordinates) {
    // write your code here
}
xCoordinates[1,4]
yCoordinates[1,4]
expected5
checking account