LeetCode 2511. Maximum Enemy Forts That Can Be Captured

You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -10, or 1 where:

  • -1 represents there is no fort at the ith position.
  • 0 indicates there is an enemy fort at the ith position.
  • 1 indicates the fort at the ith the position is under your command.

Now you have decided to move your army from one of your forts at position i to an empty position j such that:

  • 0 <= i, j <= n - 1
  • The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j)forts[k] == 0.

While moving the army, all the enemy forts that come in the way are captured.

Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.

Example 1:

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.
- Moving the army from position 8 to position 3 captures 4 enemy forts.
Since 4 is the maximum number of enemy forts that can be captured, we return 4.

Example 2:

Input: forts = [0,0,1,-1]
Output: 0
Explanation: Since no enemy fort can be captured, 0 is returned.

Constraints:

  • 1 <= forts.length <= 1000
  • -1 <= forts[i] <= 1

这道题难在阅读理解上,给了个巨复杂的情景,本质就是让你求相邻两个1 / -1之间最多有多少个0。诶,其实也有一点被卡,没有想到可以用two pointers来做。一个i每次一个个往后挪,另一个j就每次当i不是0的时候跳到i的位置。当i不是0的时候,判断j是否是i的相反数,如果是的话就可以update result了。

class Solution {
    public int captureForts(int[] forts) {
        int result = 0;
        int i = 0;
        int j = 0;
        while (i < forts.length) {
            if (forts[i] != 0) {
                if (forts[j] == -forts[i]) {
                    result = Math.max(result, i - j - 1);
                }
                j = i;
            }
            i++;
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值