---
# System prepended metadata

title: 2511. Maximum Enemy Forts That Can Be Captured
tags: [Leetcode, Two Pointers, Easy]

---

# 2511. Maximum Enemy Forts That Can Be Captured
###### tags: `Leetcode` `Easy` `Two Pointers`
Link: https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured/description/
## 思路
一个指针i往前走
一个指针ii记录上一个1或者-1的位置
如果forts[ii]+forts[i]==0说明可以攻击 那么i-ii-1就是备选答案
## Code
```java=
class Solution {
    public int captureForts(int[] forts) {
        int ans = 0;
        for(int i=0, ii=0; i<forts.length; i++){
            if(forts[i]!=0){
                if(forts[ii]+forts[i]==0){
                    ans = Math.max(ans, i-ii-1);
                }
                ii = i;
            }
        }
        return ans;
    }
}
```