-2

We having an array eg: a[], I need to pass some values randomly in to this, eg:a[98,75,65,102,35,85,6].

If I subtract the value from before element (65-75=-10), coming to 98 we can't subtract it because we are not having the previous element, so we can leave it. When we subtract all the element with its previous number we will get some value, I need to display that highest value in the output.

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
mahesh babu
  • 31
  • 1
  • 7
  • 3
    Please share the relevant parts of your code. – Altay Mazlum Jul 22 '15 at 12:00
  • also the EXACT expected output for the example input - not sure why you show 7 element array, and only discuss the 3rd, 2nd and 1st elements in that order ... no idea what you expect the **result** to be – Jaromanda X Jul 22 '15 at 12:02
  • Is your desired output the largest difference between any two adjacent numbers in the array, or the largest difference between the biggest and smallest numbers in the array, or...? What would the output be for the array you show? – nnnnnn Jul 22 '15 at 12:03
  • 98 cannot be subtract because it is not having the previous element,75-98= -23,65-75= -10, 102-65 = 37, 35-102 = -67...,so now the values that what i got isa[-23,-10,37,-67..], i want to print the biggest number in this array. – mahesh babu Jul 22 '15 at 13:11

3 Answers3

0

At first we have arrary a

var a = [98,75,65,102,35,85,6];

and lets declare the new array a1:

var a1 = [];

lets run a loop that fill this array by subtracting each element(except first element) with previous element.

for (var i = 1; i < a.length; i++) {
    a1.push(a[i-1]-a[i]);
}

then we will get a1 as:

a1 = [23, 10, -37, 67, -50, 79];

Thus, we can apply different method to get max from array as in this article and one that is prefer is

var max = Math.max.apply(Math, a1);

At last, max is 79

Hope, this will help :)

Community
  • 1
  • 1
0

Please check the following code:

var arr = [98, 75, 65, 102, 35, 85, 6];
var max = undefined;
for (var i = 0; i < arr.length - 1; i++) {
    var dif = arr[i + 1] - arr[i];
    if (max === undefined || dif > max) {
        max = dif;
    }
}
console.log(max);

For convenience please check this in JSFIDDLE.

marianc
  • 439
  • 1
  • 4
  • 13
0

This is a classical application for "reduce"--we are trying to reduce an array down to a single number. The basic form is

a.reduce(findLargestDifference)

Where findLargestDifference is a function which is passed the most recent reduced value, the element, the index, and the original array:

function findLargestDifference(cur, elt, idx, arr) {
  var diff = arr[idx-1] - elt;
  return idx === 1 ? diff : diff > cur ? diff : cur;
}