code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

016 Array Maximal Adjacent Difference

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.

Example

For inputArray = [2, 4, 1, 0], the output should be arrayMaximalAdjacentDifference(inputArray) = 3.
*/

function arrayMaximalAdjacentDifference(values) {
  let maxAbsoluteDifference = Math.abs(values[1] - values[0])
  for (let index = 0; index < values.length; index++) {
    const absoluteDifference = values[index - 1] - values[index]
    if (absoluteDifference > maxAbsoluteDifference) {
      maxAbsoluteDifference = absoluteDifference
    }
  }
  return maxAbsoluteDifference
}

test('array MaximalAdjacent Difference', () => {
  expect(arrayMaximalAdjacentDifference([2, 4, 1, 0])).toEqual(3)
})

Created 2019-12-09T02:17:09+05:30 · Edit