703896. Maximum size of consecutives

Easy

Maximum size of consecutives

Slug: maximum-size-of-consecutives3154

Difficulty: Easy

Id: 703896

Topic Tags: Arrays, Data Structures

Company Tags: None

Summary

Given an array of integers, find the maximum size of consecutive elements that are the same. For example, if the input array is [1, 2, 3, 4, 5, 6, 7, 8], the output would be 1 because there are no consecutive duplicates.

Detailed Explanation

To solve this problem, we can iterate through the array and keep track of the current sequence length. When we encounter a different element, we update the maximum sequence length if necessary. We also reset the current sequence length to 1 at that point.

Here's a step-by-step breakdown:

  1. Initialize maxSequenceLength and currentSequenceLength to 1.
  2. Iterate through the array:
    • For each element, check if it's the same as the previous one.
    • If it is, increment currentSequenceLength.
    • If not, update maxSequenceLength if necessary and reset currentSequenceLength to 1.
  3. Return maxSequenceLength.

Time complexity: O(n), where n is the length of the input array. We only iterate through the array once.

Space complexity: O(1), since we only use a few variables to keep track of the sequence lengths.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxConsecutiveDuplicates(int[] arr) {
    int maxSequenceLength = 1;
    int currentSequenceLength = 1;

    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == arr[i - 1]) {
            currentSequenceLength++;
        } else {
            maxSequenceLength = Math.max(maxSequenceLength, currentSequenceLength);
            currentSequenceLength = 1;
        }
    }

    return Math.max(maxSequenceLength, currentSequenceLength);
}

DevExCode

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

© 2026 DevExCode. All rights reserved.