Friday, March 21, 2014

Finding the biggest difference between sorted array values

Problem
finding the biggest difference between sorted array values

Example 
Consider the array : 
var array = array(1,4,7,8,12,15);
The values in the array will always be integers and is sorted, and elements may repeat.

Now, we want to print out the biggest step in the array. step is difference between adjacent element:
step array - (-,3,3,1,4,3)

The biggest step is 4, between 8 and 12.


Solution

Method 1- Brute force


var max=0;
for (i=1; i<array.length; i++)
    max = Math.max(max,array[i]-array[i-1]);

Reference - stackoverflow

0 comments:

Post a Comment