Min Cost to Connect All Points
1 approach, code in every language
Problem description
You are given an array of distinct points on a 2D plane, where each point is written as [x, y]. The cost of connecting two points equals the Manhattan distance between them, that is |x1 - x2| + |y1 - y2|.
Every point must end up connected to every other point, directly or through intermediate points, and there must be exactly one simple path between any two points. Return the minimum total cost that achieves this.
Example 1
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Connecting the points with the edges of total weight 20 links every point while keeping the sum of Manhattan distances as small as possible.
Example 2
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Constraints
1 <= points.length <= 1000-10^6 <= xi, yi <= 10^6All pairs (xi, yi) are distinct.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Trenching the Sprinkler Valves is our own problem on the technique behind Min Cost to Connect All Points: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free