LeetCode 2511: Maximum Enemy Forts That Can Be Captured
Problem Description
Explanation:
To solve this problem, we can iterate through the array and track the number of enemy forts captured starting from each friendly fort. We can do this by counting the number of zeros encountered and updating the maximum captured forts accordingly.
Algorithmic Idea:
- Iterate through the array.
- If we encounter a friendly fort (value 1), start counting the number of enemy forts after it until the next friendly fort or the end of the array.
- Update the maximum captured forts if the count is higher.
- Repeat the process for each friendly fort.
- Return the maximum captured forts.
Time Complexity:
The time complexity of this solution is O(n), where n is the length of the input array.
Space Complexity:
The space complexity of this solution is O(1) as we are using constant extra space.
:
Solutions
class Solution {
public int maxEnemyForts(int[] forts) {
int maxForts = 0;
int n = forts.length;
for (int i = 0; i < n; i++) {
if (forts[i] == 1) {
int count = 0;
for (int j = i + 1; j < n; j++) {
if (forts[j] == 0) {
count++;
} else if (forts[j] == 1) {
break;
}
}
maxForts = Math.max(maxForts, count);
}
}
return maxForts;
}
}
Loading editor...