703293. Maximum number of zeroes

Easy

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:

  1. Initialize max_zeroes and current_zeroes to 0.
  2. Iterate through the array:
    • If the current element is 0, increment current_zeroes.
    • If the current element is not 0, update max_zeroes with the maximum of its current value and current_zeroes. Reset current_zeroes to 0.
  3. 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

View on GeeksforGeeks
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);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.