Maximum Enemy Forts That Can Be Captured Problem
Description
LeetCode Problem 2511.
You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where:
-1represents there is no fort at thei^thposition.0indicates there is an enemy fort at thei^thposition.1indicates the fort at thei^ththe position is under your command.
Now you have decided to move your army from one of your forts at position i to an empty position j such that:
0 <= i, j <= n - 1- The army travels over enemy forts only. Formally, for all
kwheremin(i,j) < k < max(i,j),forts[k] == 0.
While moving the army, all the enemy forts that come in the way are captured.
Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.
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.
Constraints:
1 <= forts.length <= 1000-1 <= forts[i] <= 1
Solution
Approach: Two Pointers
A move goes from one of our forts (1) over a run of enemy forts (0) to an empty position (-1), or the other way round. So we look for a nonzero cell followed by a run of zeros and then another nonzero cell with the opposite sign.
For each nonzero position i, advance j to the next nonzero cell. If forts[i] + forts[j] == 0, the run captures j - i - 1 forts; keep the maximum. Then continue from j.
Complexity: O(n) time and O(1) space.
class Solution:
def captureForts(self, forts: List[int]) -> int:
n = len(forts)
i = ans = 0
while i < n:
j = i + 1
if forts[i]:
while j < n and forts[j] == 0:
j += 1
if j < n and forts[i] + forts[j] == 0:
ans = max(ans, j - i - 1)
i = j
return ans