2511. Maximum Enemy Forts That Can Be Captured
Description
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 theithposition.0indicates there is an enemy fort at theithposition.1indicates the fort at theiththe 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
Solutions
Solution 1: Two Pointers
Thinking
A move starts at a friendly fort, crosses a run of empty cells, and stops at an enemy fort; the captured count is the zeros in between. \(n\le 1000\) allows enumerating endpoints, but each \(i\) need not rescan to the right.
Park \(i\) on a nonzero cell and let \(j\) skip the following zeros to the next nonzero. Opposite signs mean \(j-i-1\) zeros can update the answer; then set \(i\) to \(j\) so the array is walked once.
We use a pointer \(i\) to traverse the array \(forts\), and a pointer \(j\) to start traversing from the next position of \(i\) until it encounters the first non-zero position, i.e., \(forts[j] \neq 0\). If \(forts[i] + forts[j] = 0\), then we can move the army between \(i\) and \(j\), destroying \(j - i - 1\) enemy forts. We use the variable \(ans\) to record the maximum number of enemy forts that can be destroyed.
The time complexity is \(O(n)\), and the space complexity is \(O(1)\). Where \(n\) is the length of the array forts.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |