#2511

Maximum Enemy Forts That Can Be Captured

pupil · 540 · lc easy +28 · verified · 41.1% accepted · 329 likes · top 21%

Description

Given a 0-indexed integer array forts where -1 means no fort, 0 is an enemy fort, and 1 is one of your forts, move your army from a position with value 1 to a position with value -1 passing only through consecutive enemy forts (0s). All enemy forts crossed are captured. Return the maximum number of enemy forts you can capture in one such move, or 0 if no valid move exists.

Example 1:

Input: forts = [1,0,0,-1,0,0,0,0,1]
Output: 4
Explanation:
- Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2.
- Moving the army from position 8 to position 3 captures 4 enemy forts.
Since 4 is the maximum number of enemy forts that can be captured, we return 4.

Example 2:

Input: forts = [0,0,1,-1]
Output: 0
Explanation: Since no enemy fort can be captured, 0 is returned.

Code

1
2
3