#2511
Maximum Enemy Forts That Can Be Captured
EasyArrayTwo PointersTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass to identify all forts under your command and then uses a two-pointer technique to efficiently count enemy forts between them. This reduces unnecessary checks and improves performance.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers to traverse the forts array.
- 2Step 2: For each fort under your command, move the left pointer to find the nearest empty position on the left and the right pointer to find the nearest empty position on the right.
- 3Step 3: Count the enemy forts between the two pointers and update the maximum captured.
solution.py19 lines
1# Full working Python code
2
3def maxEnemyForts(forts):
4 max_captured = 0
5 n = len(forts)
6 for i in range(n):
7 if forts[i] == 1:
8 left = i - 1
9 right = i + 1
10 captured = 0
11 while left >= 0 and forts[left] == 0:
12 captured += 1
13 left -= 1
14 while right < n and forts[right] == 0:
15 captured += 1
16 right += 1
17 max_captured = max(max_captured, captured)
18 return max_captured
19ℹ
Complexity note: This complexity is achieved because we only traverse the array once, checking each fort under your command and counting enemy forts in a single pass.
- 1Identify forts under your command first.
- 2Use two pointers to efficiently count enemy forts.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.