The maximum number of consecutive equal elements. Given a sequence of integer numbers ending with the number 0, determine the length of the longest contiguous segment where all the elements are equal to each other.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
previous_num = None current_streak = 0 longest_streak = 0 while True: num = int(input()) if num == 0: break if num == previous_num: current_streak += 1 else: if current_streak > longest_streak: longest_streak = current_streak current_streak = 1 previous_num = num if current_streak > longest_streak: longest_streak = current_streak print(longest_streak) |
Explanation of the Code
- Initialize Variables:
previous_num = None
current_streak = 0
longest_streak = 0
- Initialize
previous_num
to None
to track the previous number in the sequence.
- Initialize
current_streak
to 0 to count the current streak of equal elements.
- Initialize
longest_streak
to 0 to track the longest streak of equal elements.
- Reading Input and Finding the Longest Streak:
while True:
num = int(input())
if num == 0:
break
if num == previous_num:
current_streak += 1
else:
if current_streak > longest_streak:
longest_streak = current_streak
current_streak = 1
previous_num = num
- Use a
while True
loop to continuously read input.
- Convert the input to an integer using
int()
.
- If the integer is 0, break the loop.
- If the integer is equal to
previous_num
, increment current_streak
by 1.
- If the integer is not equal to
previous_num
, check if current_streak
is greater than longest_streak
and update longest_streak
if necessary. Then, reset current_streak
to 1 and update previous_num
to the current integer.
- Check Final Streak and Print the Longest Streak:
if current_streak > longest_streak:
longest_streak = current_streak
print(longest_streak)
- After exiting the loop, check if the final
current_streak
is greater than longest_streak
and update longest_streak
if necessary.
- Print the value of
longest_streak
.