Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Minimum Cost of Ropes

Medium Acceptance 42.73% Points 30.00

Given an array arr[] representing the lengths of ropes, the goal is to combine all the ropes into a single rope with the minimum total cost. The cost of connecting two ropes is equal to the sum of their lengths.

Examples
Example 1

Example 1

Input: arr[] = [10, 20, 30]

Output: 90

Explanation: Combine ropes 10 and 20, resulting in [30, 30]. Cost = 10 + 20 = 30. Combine ropes 30 and 30, resulting in [60]. Cost = 30 + 30 = 60. Total Cost: 30 + 60 = 90.

Example 2

Example 2

Input: arr[] = [3, 6, 8, 15]

Output: 58

Explanation: Combine the ropes in the following way to minimize the cost: Combine 3 and 6 ? Cost = 3 + 6 = 9, array becomes [9, 8, 15]. Combine 9 and 8 ? Cost = 9 + 8 = 17, array becomes [17, 15]. Combine 17 and 15 ? Cost = 17 + 15 = 32, array becomes [32]. Total Cost: 9 + 17 + 32 = 58.

Hints
Hint 1
Expected Time Complexity: O(n log n)
Hint 2
Expected Auxiliary Space: O(n)
Constraints
  • 1 <= arr.size() <= 10^5
  • 1 <= arr[i] <= 10^6
Companies
Amazon Microsoft Goldman Sachs
Topics
Queue
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions