Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum size of range in a sorted integer array

I am looking for an implementation in JavaScript for the following problem.
Consider a sorted array:

[1,2,5,9,10,12,20,21,22,23,24,26,27]

I would like to calculate the length of the maximum range that increased by 1, duplicates are not allowed.

The given example has the following ranges:

1,2
9,10
20,21,22,23,24 // the maximum range
26,27

So the return value for the given example should be 5.

I know how to solve this problem with the obvious solution, but I believe it is possible to solve the problem with more efficient and short algorithm.

like image 647
Alex Lavriv Avatar asked Feb 01 '26 02:02

Alex Lavriv


1 Answers

A short solution

I don't think this is any more efficient than what pretty much everybody else has suggested, but the code is reasonably short and only loops over the array once, except for the first element. Not sure if it's any help:

var arr = [1, 2, 5, 9, 10, 12, 20, 21, 22, 23, 24, 26, 27];
var streak = 0, best = 0, bestStart;
for (var i = 1; i < arr.length; i++) {
  if(arr[i]-arr[i-1] === 1) streak++;
  else streak = 0;
  if (streak > best) [best, bestStart] = [streak, i - streak];
}
var bestArr = arr.slice(bestStart, bestStart + best + 1);
console.log('Best streak: '+bestArr);

Speeding it up

After looking at the code, I realized that there is a way to speed it up slightly, by not checking the last few elements of the array, based on the previous value of best:

var arr = [1, 2, 5, 9, 10, 12, 20, 21, 22, 23, 24, 26, 27];
var streak = 0, best = 0, bestStart;
for (var i = 1; i < arr.length; i++) {
  if(best > arr.length - i + streak) break;
  if(arr[i]-arr[i-1] === 1) streak++;
  else streak = 0;
  if (streak > best) [best, bestStart] = [streak, i - streak];
}
var bestArr = arr.slice(bestStart, bestStart + best + 1);
console.log('Best streak: '+bestArr);
like image 52
Angelos Chalaris Avatar answered Feb 03 '26 17:02

Angelos Chalaris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!