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
๐Ÿฐ Fort Capture Battle StrategyFRIENDLYENEMYENEMYENEMYEMPTYARMY MOVEMENT PATHSTARTEND๐Ÿ“‹ Strategic Analysisโš”๏ธ Battle Plan:โ€ข Move army from friendly fort through enemy territoryโ€ข Capture all enemy forts along the direct pathโ€ข Destination must be an empty position for strategic advantage๐ŸŽฏ Result:โ€ข 3 enemy forts captured in single movementโ€ข Optimal strategy achieved with O(n) efficiencyโ€ข Maximum possible captures for this battlefield
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.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen