Priority queue · Medium
A file-compaction service repeatedly joins two batches. Each join costs the combined lengths and produces one batch of that length for later joins. The choice of merge order changes the total work; simply adding the original lengths counts only one stage.
Return the minimum total cost needed to combine all supplied batch lengths into one by repeatedly merging exactly two batches.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ lengths: integer[] }
Fields
- lengths contains non-negative integer batch lengths. Equal lengths belong to different batches.
Output
Return value
- Return the total numeric cost of all merges. Zero or one batch requires no merge and returns zero.
- A merged length is inserted back into the available batches and may be merged again.
Constraints
- 0 <= lengths.length <= 100000; 0 <= lengths[i] <= 1000000000. The exact total fits a safe JSON integer.
Examples
Example 1
{
"lengths": [
1,
2,
9
]
}Returns
15Example 2
{
"lengths": [
4
]
}Returns
0Required complexity
O(n log(n + 1)) time and O(n) auxiliary space