← Questions

Remove k consecutive machines to minimize strength differences

0
AmazonCodingLast asked Aug 2025

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), where start is the index of the first removed machine. On a tie, return the smallest start.

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, where n = len(strengths); strengths may be negative.
  • Sums can exceed 32 bits.
  • Target O(n).

Clarifying questions

  • Must exactly k machines be removed, or at most k?
  • 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-1 leaves 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 + 1 starts 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 k machines, not necessarily consecutive.
  • Remove one block of any length, paying a fixed cost per machine removed.
  • Answer many queries with different k on 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

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