Greedy Task Merging and Segment Removal Cost
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests greedy heap-based merge cost minimization and prefix-sum sliding-window removal to minimize adjacent absolute differences.
Greedy Task Merging and Segment Removal Cost
You will implement two independent cost-minimization routines, packaged together in a single function.
Part 1 — Optimal Task Consolidation
You have a list of tasks, each with a positive integer size. In one operation you pick any two tasks of sizes a and b, combine them into a single task of size a + b, and pay a cost of a + b. Repeat until only one task remains.
Return the minimum total cost to fully consolidate all tasks.
- If the list is empty or contains exactly one task, no operations are needed and the cost is
0.
Part 2 — Best Segment Removal
You have an array of integer values and a positive integer k. Remove exactly k consecutive elements (a contiguous block) from the array. For the elements that remain — kept in their original relative order — compute the roughness: the sum of |value[i] − value[i+1]| over every adjacent pair in the remaining sequence.
Find the removal that produces the smallest roughness. Return that minimum roughness together with the starting index (0-based, in the original array) of the removed block.
- If multiple starting positions yield the same minimum roughness, return the smallest such starting index.
- It is guaranteed that
1 ≤ k < len(values), so at least one element always remains.
Return value
Return a single list in this exact format:
[merge_cost, [min_roughness, best_start_index]]
where merge_cost is the answer to Part 1 and [min_roughness, best_start_index] is the answer to Part 2.
Constraints
0 ≤ len(tasks) ≤ 10^4; each task size is a positive integer≤ 10^5.2 ≤ len(values) ≤ 10^5; each value is an integer in[−10^9, 10^9].1 ≤ k < len(values).- Aim for O(m log m) on Part 1 (where
m = len(tasks)) and O(n) on Part 2 (wheren = len(values)).
Examples
Example 1
Input: compute_array_costs([1, 2, 3, 4], [1, 3, 2, 5, 4], 2)
Output: [19, [3, 2]]
Example 2
Input: compute_array_costs([5], [10, 1, 8, 3], 1)
Output: [0, [7, 1]]
Example 3
Input: compute_array_costs([4, 2, 7], [9, 2, 6, 1, 8, 3], 3)
Output: [19, [6, 1]]
Hints
Hint 1
For Part 1, think about what determines how many times each original task size contributes to the total cost. That framing points directly to a well-known greedy tree-building algorithm that uses a min-heap.
Hint 2
For Part 2, instead of recomputing the full roughness from scratch for each window, precompute a prefix array of the adjacent absolute differences. Then express each candidate removal's roughness as three pieces: edges entirely on the left, edges entirely on the right, and at most one new bridge edge where the two surviving segments meet.
Hint 3
Watch the index arithmetic on the right-side prefix sum. The edge between positions `end` and `end+1` involves a removed element, so it must be excluded. Also remember that when the removed block starts at index 0 or ends at the last index, there is no bridge edge to add.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Optimal Task Consolidation
Every merge produces a new item whose size equals the sum of its two inputs. If you picture all the merges as a binary tree, each original task size gets multiplied by the depth of its leaf. The total cost is therefore the weighted path length of that tree, which is exactly what Huffman's algorithm minimizes.
The procedure:
- Load all task sizes into a min-heap.
- Repeatedly pop the two smallest values, add them together, accumulate that sum into the running total, and push the sum back onto the heap.
- Stop when one item remains.
Why the greedy choice is safe: by an exchange argument, the two smallest tasks must be siblings at the deepest level in any optimal tree. Merging them first reduces the problem by one item while preserving optimality. Induction closes the argument.
A common wrong approach is to sort once and merge left-to-right. That fails because a merged sum can exceed tasks not yet processed, so the heap must be consulted after every merge.
Time: O(m log m) — m − 1 merges, each doing O(log m) heap work.
Space: O(m) for the heap.
Part 2 — Best Segment Removal
Label the edge between positions i − 1 and i as e[i] = |values[i] − values[i−1]|. Build a prefix array:
edge_prefix[0] = 0
edge_prefix[i] = e[1] + e[2] + ... + e[i] for i >= 1
When the block [start, end] (with end = start + k − 1) is removed, the roughness of what remains has up to three parts:
- Left edges (inside the surviving left segment):
edge_prefix[start − 1], only whenstart > 0. - Right edges (inside the surviving right segment):
edge_prefix[n − 1] − edge_prefix[end + 1], only whenend + 1 < n. The subtraction excludes the edge atend + 1, which touches a removed element. - Bridge edge (the new adjacency between the two segments):
|values[start − 1] − values[end + 1]|, only when both segments are non-empty.
Each window is evaluated in O(1), and all n − k + 1 windows are tried, so the global minimum is found exactly. Ties go to the smallest start index because the loop runs left to right and the update condition is strict <.
Time: O(n) — one pass for the prefix array, one pass for the window scan.
Space: O(n) for the prefix array.
Edge cases
- Empty or single-element
taskslist → merge cost is 0 (thewhileloop never executes). start = 0orend = n − 1→ no bridge edge, handled by the boundary checks.k = n − 1→ one element remains, roughness is 0 forstart = 0.
Full solution
import heapq
from typing import List
def compute_array_costs(tasks: List[int], values: List[int], k: int) -> List[int]:
# ── Part 1: greedy heap merging (Huffman-style) ──────────────────────────
heap = list(tasks)
heapq.heapify(heap)
merge_cost = 0
while len(heap) > 1:
merged = heapq.heappop(heap) + heapq.heappop(heap)
merge_cost += merged
heapq.heappush(heap, merged)
# ── Part 2: prefix sums of adjacent absolute differences ─────────────────
n = len(values)
# edge_prefix[i] = sum of |values[j] - values[j-1]| for j in 1..i
edge_prefix = [0] * n
for i in range(1, n):
edge_prefix[i] = edge_prefix[i - 1] + abs(values[i] - values[i - 1])
best_cost = None
best_start = 0
for start in range(n - k + 1):
end = start + k - 1
cost = 0
# Edges entirely within the left surviving segment [0 .. start-1]
if start > 0:
cost += edge_prefix[start - 1]
# Edges entirely within the right surviving segment [end+1 .. n-1]
# edge_prefix[end+1] includes the edge between end and end+1 (removed),
# so subtract up to and including index end+1.
if end + 1 < n:
cost += edge_prefix[n - 1] - edge_prefix[end + 1]
# One new bridge edge where the two surviving segments meet
if start > 0 and end + 1 < n:
cost += abs(values[start - 1] - values[end + 1])
# Keep smallest cost; ties broken by smallest start index
if best_cost is None or cost < best_cost:
best_cost = cost
best_start = start
return [merge_cost, [best_cost, best_start]]