Lv.2greedyheap
Minimum Cost to Join Ropes
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 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
| ropes | result |
|---|---|
[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
-
ropes.length,ropes[i]; the answer can exceed 32 bits.
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| ropes | Expected |
|---|---|
[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 .
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1330 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 6 | verdict only |
| performance | 60 | 4 | verdict only |