You are given an integer array forts
of length n representing the positions of enemy forts, your forts, and empty positions between them. The value of forts[i]
can be one of three possible scenarios:
1
represents your fort at position i
-1
represents an enemy fort at position i
0
represents an empty position at position i
You want to calculate the maximum number of enemy forts that can be captured in a single move. A move involves capturing all enemy forts between two of your forts (i.e., between two 1
s) without encountering any other obstruction (enemy forts are not obstructed in this case). Therefore, the forts you capture must be uninterrupted. The task is to return the maximum number of contiguous -1
values that can be captured in a single move.
1
on both ends)?
n == forts.length
where 1 <= n <= 1000
and the values in forts
can only be -1
, 0
, or 1
.1
s.-1
s it contains.-1
s) that can be captured between any two 1
s.This algorithm involves a single pass through the array (O(n)) with some additional operations which makes it efficient given the constraints.
def captureForts(forts):
n = len(forts)
max_enemies = 0
i = 0
while i < n:
if forts[i] == 1:
j = i + 1
enemy_count = 0
while j < n and forts[j] != 1:
if forts[j] == -1:
enemy_count += 1
j += 1
if j < n and forts[j] == 1: # Valid segment between two '1's
max_enemies = max(max_enemies, enemy_count)
i = j # Move to the next potential starting '1'
else:
i += 1
return max_enemies
forts
array. This linear complexity arises from traversing the array once and checking each segment.By following these steps, the function efficiently determines the maximum number of contiguous enemy forts that can be captured in a single move.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?