[LeetCode] Maximum Enemy Forts That Can Be Captured

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 -1, 0, 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
int captureForts(vector<int>& forts) {
int left = INT_MAX, right = INT_MIN;
int res = 0;
for(int i = 0; i < forts.size(); i++) {
if(forts[i] == -1) left = i;
if(forts[i] != 1) continue;
if(right <= i) {
right = i;
while(right < forts.size() and forts[right] != -1) right += 1;
}
if(left != INT_MAX) {
int now = 0;
for(int j = left + 1; j < i; j++) {
if(forts[j] == 0) now += 1;
else {
now = 0;
break;
}
}
res = max(res, now);
}
if(right != forts.size()) {
int now = 0;
for(int j = i + 1; j < right; j++) {
if(forts[j] == 0) now += 1;
else {
now = 0;
break;
}
}
res = max(res, now);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/25/PS/LeetCode/maximum-enemy-forts-that-can-be-captured/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.