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:
- Initialize
maxSequenceLengthandcurrentSequenceLengthto 1. - 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
maxSequenceLengthif necessary and resetcurrentSequenceLengthto 1.
- 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
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);
}