i holds piles[i] buckets. In one move you take exactly group **adjacent** piles and pour them into one; the move costs the total number of buckets in those piles. The new pile takes their place in the row.
Return the minimum total cost to gather all the sand into a single pile, or -1 if that is impossible.piles=[4, 1, 2, 6], group=2 → 23
Merge 1 and 2 (cost 3), then 4 and 3 (cost 7), then 7 and 6 (cost 13). The total of 23 is the best possible.
piles=[5, 5], group=3 → -1
There are only two piles but merges take three at a time, so one pile can never be formed.
piles=[2, 7, 1, 3, 5], group=3 → 27
piles) ≤ 30piles[i] ≤ 100group ≤ 30piles=[4, 1, 2, 6], group=2
23
Run checks the first 3 tests in your browser. Submit checks all 219 tests on the server, hidden ones included.