Skip to content

ORIGINAL CODING QUESTION

Merge neighbouring report piles

Report piles stand in a row with given page counts. One step merges two NEIGHBOURING piles into a single pile in their place and costs the combined page count. Keep merging until one pile remains and return the minimum total cost. Because only neighbours may merge, the two smallest piles are not always available together.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n page counts in row order.

Constraints

1 ≤ n ≤ 8; 1 ≤ pages ≤ 100.

Example 1

Input

4 4 1 1 4

Output

18

Merge 1+1 (2), then 4+2 (6), then 6+4 (10): total 18.

Example 2

Input

1 9

Output

0

A single pile needs no merging.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

The final merge joins a left block and a right block of the original row.

Hint 2

Merging any block costs its page total once at the end plus the cost of building each side.

Hint 3

best[i][j] = min over split k of best[i][k] + best[k+1][j] + pages(i..j), using prefix sums.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →