Skip to the code
+50 XP

#179 Best Spot for a Floating Toolbar

hard

A text editor shows a floating toolbar along a horizontal line. Users click buttons that sit at the x positions in positions, and weights[i] is how many times per minute the button at positions[i] is clicked. If the toolbar sits at x, a click on button i costs weights[i] × |x - positions[i]| of mouse travel.

Write minTravel(positions, weights) that returns the smallest total travel per minute over every real position x. Answers within 1e-5 count as correct.

Hint at the shape: the total travel is a sum of V-shaped functions, so it falls and then rises as x moves right (it may be flat at the bottom).

Example 1

Input: positions = [0,10], weights = [1,3]
Output: 10

Put the toolbar at 10: only the light button at 0 travels, costing 1 × 10.

Example 2

Input: positions = [1,2,3], weights = [1,1,1]
Output: 2

At x = 2, the travel is 1 + 0 + 1.

Constraints

  • 1 <= positions.length <= 10^5
  • weights.length === positions.length
  • -10^6 <= positions[i] <= 10^6
  • 1 <= weights[i] <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).