Maximum Enemy Forts That Can Be Captured - Problem
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-thposition 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.
Input & Output
Example 1 — Basic Capture
$
Input:
forts = [1,0,0,-1,0,0,0,-1]
›
Output:
4
💡 Note:
Move army from position 0 (fort 1) to position 7 (empty -1), capturing 4 enemy forts at positions 1,2,4,5,6. Path: 1→0→0→-1→0→0→0→-1 captures enemies at positions 4,5,6 (3 enemies) or from position 3 to end capturing 3 enemies.
Example 2 — No Valid Path
$
Input:
forts = [0,0,1,0]
›
Output:
0
💡 Note:
No valid path exists because there's no empty position (-1) to move to from the friendly fort at position 2.
Example 3 — Multiple Options
$
Input:
forts = [1,0,0,-1,1,0,-1]
›
Output:
2
💡 Note:
Can move from position 0 to position 3 capturing 2 enemies, or from position 4 to position 6 capturing 1 enemy. Maximum is 2.
Constraints
- 1 ≤ forts.length ≤ 1000
- -1 ≤ forts[i] ≤ 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with 1 (friendly), 0 (enemy), -1 (empty) positions
2
Find Valid Paths
Look for paths from 1 to -1 through only 0s
3
Count Maximum
Return the maximum enemies captured in any valid path
Key Takeaway
🎯 Key Insight: Valid moves must go between different boundary types (1↔-1) through consecutive enemies only
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code