Skip to content

2511. Maximum Enemy Forts That Can Be Captured

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int captureForts(vector<int>& forts) {
    int ans = 0;

    for (int i = 0, j = 0; i < forts.size(); ++i)
      if (forts[i] != 0) {  // -1 or 1
        if (forts[i] == -forts[j])
          ans = max(ans, i - j - 1);
        j = i;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int captureForts(int[] forts) {
    int ans = 0;

    for (int i = 0, j = 0; i < forts.length; ++i)
      if (forts[i] != 0) { // -1 or 1
        if (forts[i] == -forts[j])
          ans = Math.max(ans, i - j - 1);
        j = i;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def captureForts(self, forts: list[int]) -> int:
    ans = 0

    j = 0
    for i, fort in enumerate(forts):
      if fort != 0:  # -1 or 1
        if fort == -forts[j]:
          ans = max(ans, i - j - 1)
        j = i

    return ans