[LeetCode] 2511. Maximum Enemy Forts That Can Be Captured

发布时间 2023-09-02 01:18:34作者: CNoodle

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

最多可以摧毁的敌人城堡数目。

给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中:

  • -1 表示第 i 个位置 没有 城堡。
  • 0 表示第 i 个位置有一个 敌人 的城堡。
  • 1 表示第 i 个位置有一个你控制的城堡。

现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足:

  • 0 <= i, j <= n - 1
  • 军队经过的位置 只有 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。

当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。

请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。

我分享一个扫描一遍的思路。遍历 input 数组,如果遇到非 0 的数字,就记一下当前位置,接着往后走,如果再次遇到一个非 0 的数字,需要检查一下这个数字是否是之前一个非 0 数字的相反数(1 或者 -1),只有是相反数我们才统计一下两者之间的间距,最后全局最大的间距就是能摧毁的城堡数目。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int captureForts(int[] forts) {
 3         int pre = -1;
 4         int cur = -1;
 5         int res = 0;
 6         for (int i = 0; i < forts.length; i++) {
 7             if (forts[i] == 1 || forts[i] == -1) {
 8                 cur = i;
 9                 if (pre != -1 && forts[i] == -forts[pre]) {
10                     res = Math.max(res, i - pre - 1);
11                 }
12                 pre = cur;
13             }
14         }
15         return res;
16     }
17 }

 

LeetCode 题目总结