I would like to write a function that takes in an array of integers and returns an array of length 2 that represents the largest range of integers contained in that array.
A range is defined as a set of consecutive numbers in the set of integers. For example, the output array [2, 6]
represents the range {2, 3, 4, 5, 6}
.
Assume non-empty arrays and one largest range only.
Sample Input: array[1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6]
Sample Output: [0, 7]
The code below works for the example above but fails for the following input, for example: array[8, 4, 2, 10, 3, 6, 7, 9, 1]
whose output should be [6, 10]
. My code produces [1, 4]
.
Can someone help, please?
def largestRange(array):
array.sort()
initial = array[0]
start_idx = initial
final = initial
last_idx = final
length = 0
size = (final - initial + 1)
for i in range(1,len(array)):
if array[i] - array[i-1] == 1 and i < len(array) - 1:
final += 1
elif array[i] - array[i-1] == 1 and i == len(array) - 1:
final +=1
if size > length:
start_idx = initial
last_idx = final
else:
if size > length:
start_idx = initial
last_idx = final
length = size
initial = array[i]
final = initial
return [start_idx, last_idx]
(The idea is to update the values of start_idx
and last_idx
everytime the sequence breaks and size > length
)