EasyNo. 2511

Maximum Enemy Forts That Can Be Captured — LeetCode 2511 Python Solution

Topics
Array, Two Pointers
Reading time
3 min

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

PythonSolution
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 ans

Complexity

Time
O(n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
00153SumMedium
00163Sum ClosestMedium
00184SumMedium
0026Remove Duplicates from Sorted ArrayEasy
0027Remove ElementEasy
0031Next PermutationMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.