Maximize protected population with one-step guard shifts
AmazonSoftware Engineer · Online AssessmentLast updated
This question evaluates the ability to reason about constrained local moves and optimize a numerical objective over an array, testing skills in array manipulation, combinatorial optimization, and interpretation of binary state representations.
There are n cities in a line (1-indexed). You are given:
population[1..n]: population of each cityunit: a binary string of lengthn, whereunit[i] = '1'means cityiinitially has a security guard, andunit[i] = '0'means it does not.
A guard may be moved at most once. A move consists of shifting a guard from city i to city i-1 (one step left), only if:
i > 1, and- city
i-1currently has no guard.
You may perform moves in any order.
After all moves, the “protected population” is the sum of populations of the cities that end up with a guard.
Compute the maximum protected population achievable.
Example:
population = [10, 5, 8, 9, 6]unit = "01101"
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.