← Questions
Remove k consecutive machines to minimize strength differences
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Aug 2025. It tests prefix sums and sliding window.
Machines stand in a row, each with an integer strength. Remove exactly k consecutive machines. The cost of the remaining row, kept in its original order, is the sum of |strength[i] - strength[i+1]| over every pair of neighbours. Return the smallest possible cost and the start index of a block that achieves it.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_remaining_cost(strengths: list[int], k: int) -> tuple[int, int]— returns(cost, start), wherestartis the index of the first removed machine. On a tie, return the smalleststart.
Example
min_remaining_cost([1, 100, 2, 3, 4], 1) -> (3, 1) # remove 100: [1, 2, 3, 4]
min_remaining_cost([10, 1, 10, 1, 10], 2) -> (18, 0) # every choice costs 18; [10, 1, 10]
min_remaining_cost([5, 1, 6, 2, 8], 2) -> (9, 1) # remove 1, 6: [5, 2, 8]
Constraints
-
1 <= k < n, wheren = len(strengths); strengths may be negative. - Sums can exceed 32 bits.
- Target O(n).
Clarifying questions
- Must exactly
kmachines be removed, or at mostk? - On a tie, which start index should be returned?
- Can the remaining row have a single machine (cost 0)?
What a strong answer covers
- Removing the block
s..s+k-1leaves three parts: differences inside the prefix, differences inside the suffix, and one new join|a[s+k] - a[s-1]|that exists only when both sides are non-empty. - Prefix sums of the adjacent differences make each candidate O(1), so the sweep over all
n - k + 1starts is O(n) time and O(n) or O(1) extra space. - The edge cases: the block at the very start or the very end (no join), and
k = n - 1. - Testing against brute force on small random arrays.
Follow-ups
- Remove at most
kmachines, not necessarily consecutive. - Remove one block of any length, paying a fixed cost per machine removed.
- Answer many queries with different
kon the same row.
Where it's asked
- Amazon · Coding · Last asked Aug 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
prefix sums · sliding window
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
