Implement two array-cost minimization algorithms
AmazonSoftware Engineer · OnsiteLast updated
This question evaluates algorithm design, data structure selection, and complexity analysis by requiring implementations for minimizing total merge cost and for removing a contiguous block to minimize the sum of adjacent absolute differences.
Implement two array-cost minimization algorithms.
- Minimize merge cost: Given a list of positive integers workloads representing task sizes, you may repeatedly merge any two items a and b into a single item of size a+b, incurring cost a+b for that merge. Implement minimizeSystemCost(workloads: int[]) -> long that returns the minimal total cost to end with one item. State the algorithm and its time/space complexity.
- Remove a contiguous block: Given an integer array machines representing machine strengths and an integer k (1 <= k < machines.length), remove exactly k consecutive elements so that, for the remaining sequence in original order, the sum over all adjacent pairs of |strength[i] - strength[i+1]| is minimized. Implement minimizeRemainingAdjDiff(machines: int[], k: int) -> (long minCost, int startIndex), returning the minimal cost and a valid starting index of the removed block. Target O(n) or O(n log n).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.