How to find the maximum distance between two same elements/integers of a list in python.
e.g. if a list is [1,3,3,5,6,4,8,6,0,3,5]
Output would be 8 (distance b/w 3's is maximum here)
You can use a dictionary where for each value you save the indices.
from collections import defaultdict
d = defaultdict(list)
for i,el in enumerate(l):
d[el].append(i)
max_dist = max(d[k][-1]-d[k][0] for k in d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With