Shift security units left to protect the most population
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) -
unitcontains 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
