I did an exercise today on where the task is to write a function that returns the length of the longest subarray where the difference between the smallest and biggest value in the subarray is no more than 1. I had a solution that works but it's too slow to pass the tests that have big arrays. What is it about my solution that makes it very slow with huge arrays?
def longestSubarray(arr):
longest = 0
arr_len = len(arr)
for i in range(arr_len):
for j in range(i, arr_len):
sub = arr[i: j+1]
if max(sub) - min(sub) > 1:
continue
length = len(sub)
if length > longest:
longest = length
return longest