Maximum Enemy Forts That Can Be Captured - Problem
You are a strategic commander with control over multiple friendly forts scattered across a battlefield. Your mission is to maximize enemy fort captures through tactical army movements!
Given an array forts representing the battlefield:
1= Your friendly fort ๐ฐ0= Enemy fort ๐-1= Empty position ๐๏ธ
Movement Rules:
- Move your army from any friendly fort to any empty position
- Your path must contain only enemy forts between start and destination
- All enemy forts on the path are automatically captured โ๏ธ
Goal: Return the maximum number of enemy forts you can capture in a single movement. If no valid movement exists, return 0.
Input & Output
example_1.py โ Basic capture scenario
$
Input:
[1,0,0,-1,0,0,1,0,0,1]
โบ
Output:
2
๐ก Note:
Move army from fort at position 0 to empty position 3, capturing 2 enemy forts at positions 1 and 2. This gives the maximum possible captures.
example_2.py โ No valid moves
$
Input:
[0,0,1,0,0]
โบ
Output:
0
๐ก Note:
No empty positions (-1) available for army movement, so no captures are possible.
example_3.py โ Multiple options
$
Input:
[-1,1,0,0,0,-1]
โบ
Output:
3
๐ก Note:
Move army from fort at position 1 to empty position 5, capturing all 3 enemy forts at positions 2, 3, and 4.
Constraints
- 1 โค forts.length โค 1000
- forts[i] is either -1, 0, or 1
- The array represents positions of forts on a battlefield
- Movement constraint: Army can only travel through enemy territory
Visualization
Tap to expand
Understanding the Visualization
1
Battlefield Assessment
Survey the battlefield to identify friendly forts (green), enemy forts (red), and empty positions (gray)
2
Pattern Recognition
Look for valid movement patterns: friendly fort โ enemy territory โ empty position
3
Route Planning
Identify the route that passes through the maximum number of enemy forts
4
Execute Movement
Move army along the optimal path, capturing all enemies en route
Key Takeaway
๐ฏ Key Insight: Valid capture sequences follow a strict pattern of boundary โ enemies โ opposite boundary. By recognizing this pattern during a single scan, we achieve optimal O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code