← Questions

Shift security units left to protect the most population

0
AmazonCodingLast asked Apr 2026

A coding interview question asked in Amazon's online assessment, last asked Apr 2026. It tests greedy, arrays and strings.

Cities stand in a row, numbered 0 to n - 1. You are given an integer array population of length n (all values >= 0) and a binary string unit of the same length. unit[i] == '1' means city i starts with one security unit; '0' means it has none.

Each unit may do one of two things: stay in its city, or move exactly one city to the left (from i to i - 1). A unit in city 0 cannot move. Each unit moves at most once.

After all units are placed, a city is protected if it holds at least one unit. Several units in one city still protect it only once.

Implement:

def max_protected(population: list[int], unit: str) -> int

Return the largest possible total population of protected cities.

Constraints

  • 0 <= n <= 10^5
  • 0 <= population[i] <= 10^9 (the answer may need 64 bits)
  • unit contains only '0' and '1'

Example 1

population = [4, 1, 9]
unit       = "011"
output     = 13

Move the unit in city 1 to city 0 and keep the unit in city 2. Cities 0 and 2 are protected: 4 + 9 = 13.

Example 2

population = [2, 9, 9, 9]
unit       = "0111"
output     = 27

City 0 is the cheapest one to leave unprotected, so no unit moves: 9 + 9 + 9 = 27.

Clarifying questions

  • Can a unit move only one city left, never right?
  • Does a unit in city 0 stay put?
  • Is an empty input answered with 0?
  • Is only the total returned, or also where each unit ends up?

What a strong answer covers

  • Splits unit into maximal runs of '1'. A run covering cities l..r with l > 0 has r - l + 1 units for the r - l + 2 cities l - 1..r: it can protect all of them but one, and any one can be the one left out.
  • So each such run adds the sum of those cities minus their minimum population; a run starting at city 0 protects exactly its own cities.
  • One pass, O(n) time and O(1) space, with 64-bit totals. A DP over cities with "a unit moved in from the right or not" also works.
  • Tests both examples, no units, all units, and alternating units.

Follow-ups

  • Units may move left or right by one city.
  • A unit may move up to d cities to the left.
  • Each move has a cost, and the goal is protected population minus moving cost.

Where it's asked

  • Amazon · Online assessment · Last asked Apr 2026Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

greedy · arrays · strings

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