File: maximum-enemy-forts-that-can-be-captured/solution.py

Date: 2026-06-06

Time: 17:37

maximum-enemy-forts-that-can-be-captured/solution.py

Purpose

Solves LeetCode 2511: Maximum Enemy Forts That Can Be Captured. The file owns a single function that computes the maximum number of enemy forts (represented as 0) that can be captured by moving your army from a friendly fort (1) to an empty position (-1), or vice versa, in a straight line over only enemy forts.

Key Components

maxcapturedforts(forts: list[int]) -> int — The sole public function. Takes a list where each element is -1 (empty), 0 (enemy fort), or 1 (your fort). Returns the maximum count of enemy forts between any valid pair of endpoints.

A "valid pair" is two non-zero values of *opposite sign* with only 0s between them.

Patterns

Anchor-tracking scan. Rather than brute-forcing all pairs (O(n^2)), the algorithm keeps a single pointer lastnonzero to the most recent index where forts[i] != 0. When the next non-zero value is found, it checks whether the two endpoints differ in sign — if so, the gap i - lastnonzero - 1 counts the enemy forts between them.

This is a standard "last-seen" idiom: skip irrelevant elements, compare the current non-zero to the previous non-zero. It runs in O(n) time and O(1) space.

Dependencies

Imports: None — pure stdlib, no external dependencies.

Imported by: The test_solution.py in its own directory. The large "Imported By" list in the prompt is an artifact of the test harness — those other test files don't actually import *this* solution; they import their own respective solutions via the same relative pattern.

Flow

1. Initialize result = 0 (best gap found) and lastnonzero = -1 (no anchor yet).

2. Iterate over forts with index i and value val.

3. If val != 0 (i.e., it's 1 or -1):

4. Return result.

Invariants

Error Handling

None. The function assumes well-formed input per the LeetCode contract. An empty list or all-zeros list returns 0 naturally (no non-zero pair is ever found).