Problem Description
Given an array where each element represents the state of a fort (1 for your fort, 0 for an enemy fort, and -1 for an empty position), you must determine the maximum number of enemy forts that can be captured. You capture enemy forts by moving your army from one of your forts to an empty position, ensuring that every position between the starting fort and the destination contains an enemy fort. If no valid move exists (or you have no fort under your command), return 0.
Key Insights
- The army can only move if the endpoints are of opposite types: one must be your fort (1) and the other an empty position (-1), with only enemy forts (0) in between.
- By iterating through the array and keeping track of the last encountered non-enemy position, we can check if a valid capturing sequence exists whenever another non-zero is found.
- The number of enemy forts captured in a valid move equals the distance between these positions minus one.
- A single pass solution with constant extra space (two pointers or index tracking) is both efficient and simple.
Space and Time Complexity
Time Complexity: O(n) because we scan the array once. Space Complexity: O(1) as we use only a few additional variables.
Solution
We solve the problem using a single pass iteration. We maintain a variable to remember the index and type (either 1 or -1) of the last encountered non-zero element. As we traverse the array:
- When a non-zero element is encountered (either 1 or -1), we check if the previously stored element exists and whether its type is the opposite of the current one.
- If it is opposite, then the segment in between (which must be all enemy forts) can be captured, and the count is the difference in indices minus one.
- We update the maximum capture count accordingly and update the last non-zero index. This approach leverages a two-pointer idea within a single loop.