Maximize protected population with one-step guard shifts
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: 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.
Constraints
- 0 <= n <= 2 * 10^5
- len(population) == len(unit)
- 0 <= population[i] <= 10^9
- unit contains only '0' and '1'
Examples
Input: ([10, 5, 8, 9, 6], "01101")
Expected Output: 27
Explanation: Move the guard from city 2 to city 1, and move the guard from city 5 to city 4. The guarded cities become 1, 3, and 4, so the protected population is 10 + 8 + 9 = 27.
Input: ([10, 1, 2, 3], "0111")
Expected Output: 15
Explanation: The block of guards at cities 2..4 is preceded by city 1 with population 10. The best choice is to leave city 2 (population 1) unguarded by moving the guard from city 2 to city 1. Total protected population is 10 + 2 + 3 = 15.
Input: ([4, 7, 2], "111")
Expected Output: 13
Explanation: All cities already have guards, and the first city has no left neighbor. No move can improve the result, so the answer is 4 + 7 + 2 = 13.
Input: ([6, 1, 5, 4, 9, 2], "101101")
Expected Output: 24
Explanation: City 1 stays guarded. For the block at cities 3..4, it is best to leave city 2 unguarded, so cities 3 and 4 remain guarded. For city 6, moving its guard to city 5 is better. Total = 6 + 5 + 4 + 9 = 24.
Input: ([], "")
Expected Output: 0
Explanation: There are no cities, so the protected population is 0.
Input: ([5], "0")
Expected Output: 0
Explanation: There is one city but no guard, so no population is protected.
Hints
- Look at maximal consecutive blocks of '1's. Blocks separated by zeros can be optimized independently.
- If a block of guards is preceded by an empty city, only a prefix of that block can shift left. Think about which single city in that extended segment could be left unguarded.