Maximum Enemy Forts That Can Be Captured — LeetCode 2511 Python Solution
- Problem
- #2511
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The 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: -1 represents there is no fort at the ith position.
Example
- Input
- forts = [1,0,0,-1,0,0,0,0,1]
- Output
- 4
- Explanation
- - Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2.
Python solution
class Solution:
def captureForts(self, forts: List[int]) -> int:
n = len(forts)
i = ans = 0
while i < n:
j = i + 1
if forts[i]:
while j < n and forts[j] == 0:
j += 1
if j < n and forts[i] + forts[j] == 0:
ans = max(ans, j - i - 1)
i = j
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2511. Maximum Enemy Forts That Can Be Captured is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2511. Maximum Enemy Forts That Can Be Captured?
- LeetCode 2511. Maximum Enemy Forts That Can Be Captured is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2511. Maximum Enemy Forts That Can Be Captured?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2511. Maximum Enemy Forts That Can Be Captured?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2511. Maximum Enemy Forts That Can Be Captured cover?
- LeetCode 2511. Maximum Enemy Forts That Can Be Captured is tagged Array and Two Pointers on LeetCode.