Funcia
Lv.2greedyheap

Minimum Cost to Join Ropes

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Joining two ropes costs the sum of their lengths and produces one rope of that length. Return the minimum total cost to join all ropes into one (0 for a single rope).

Examples

ropesresult
[4, 3, 2, 6]29
[1, 1, 1, 1]8
[10]0

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(ropes: int[]) → long

Constraints

  • 1≤1 \le ropes.length ≤200,000\le 200{,}000, 1≤1 \le ropes[i] ≤106\le 10^6; the answer can exceed 32 bits.

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

ropesExpected
[4,3,2,6]29
[1,1,1,1]8
[10]0

Hint

Hint

Always join the two shortest ropes (Huffman's argument) using a min-heap, with 64-bit sums. Scanning for the two shortest each time is O(N2)O(N^2).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251330 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness406verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.