Compare with the previous box
Find the longest run of equal values. About 9 minutes.
Compare with the box before
A fitness app shows your longest streak of days in a row with a workout. To know whether today continues the streak, it looks at yesterday.
Questions about neighbours work the same way: at each box, compare it with the box just before it. Start the loop at the second box, because the first box has nothing before it to compare with.
run = 1, best = 1.
The streak grows or starts over
Keep the length of the current streak. If this box equals the one before, the streak grows by 1. If it's different, a new streak starts, of length 1.
The current streak can drop back to 1 at any moment, so keep a second variable for the longest streak you've ever seen. For 5, 5, 1, 1, 1, 7 that's 3, the three 1s.
if not nums:
return 0
run = best = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
run += 1
else:
run = 1
best = max(best, run)
return bestWhat's the longest run of equal values next to each other?
nums = [2, 2, 3, 2, 2, 2]
- A5
- B3
- C2
Show the answer
3. The last three 2s sit next to each other. That's the longest run.
Longest run
Return the length of the longest stretch of equal values next to each other. An empty list has no runs, so return 0.
nums = [5, 5, 1, 1, 1, 7] → 3
0 ≤ n ≤ 1,000