703293. Maximum number of zeroes
Maximum number of zeroes
Slug: maximum-number-of-zeroes4048 Difficulty: Easy Id: 703293 Topic Tags: Arrays, Data Structures Company Tags: Oracle
Summary
Given an integer array arr, find the maximum number of consecutive zeroes that can be formed by replacing all non-zero elements with zeros. For example, if the input is [1, 0, 2, 3, 4], the maximum number of zeroes that can be formed would be 2 (by replacing 1 and 2 with zeros).
Detailed Explanation
To solve this problem, we need to iterate through the array and keep track of the consecutive zeroes. We can do this by initializing a variable max_zeroes to store the maximum number of zeroes found so far, and another variable current_zeroes to count the current sequence of zeroes.
Here's a step-by-step breakdown of the solution:
- Initialize
max_zeroesandcurrent_zeroesto 0. - Iterate through the array:
- If the current element is 0, increment
current_zeroes. - If the current element is not 0, update
max_zeroeswith the maximum of its current value andcurrent_zeroes. Resetcurrent_zeroesto 0.
- If the current element is 0, increment
- Return
max_zeroes.
Time complexity: O(n), where n is the length of the input array. Space complexity: O(1), as we only use a constant amount of space.
Optimized Solutions
Java
public int maxZeroes(int[] arr) {
int maxZeroes = 0;
int currentZeroes = 0;
for (int num : arr) {
if (num == 0) {
currentZeroes++;
} else {
maxZeroes = Math.max(maxZeroes, currentZeroes);
currentZeroes = 0;
}
}
return Math.max(maxZeroes, currentZeroes);
}