Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Created June 2, 2017 14:43
Show Gist options
  • Save tyler-austin/0b9a1714c9252819c0e2f731d05bb59d to your computer and use it in GitHub Desktop.
Save tyler-austin/0b9a1714c9252819c0e2f731d05bb59d to your computer and use it in GitHub Desktop.
Code Fights - arrayMaximalAdjacentDifference

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.

Input/Output

  • [time limit] 4000ms (py3)

  • [input] array.integer inputArray

    Guaranteed constraints:

    3 ≤ inputArray.length ≤ 10,
    -15 ≤ inputArray[i] ≤ 15.
    
  • [output] integer

    The maximal absolute difference.

from typing import List
class ArrayMaximalAdjacentDifference:
@classmethod
def array_maximal_adjacent_difference(cls, data: List[int]):
max_abs_dif = 0
prev = data[0]
for d in data:
abs_dif = abs(d - prev)
if abs_dif > max_abs_dif:
max_abs_dif = abs_dif
prev = d
return max_abs_dif
def arrayMaximalAdjacentDifference(data: list):
max_abs_dif = 0
prev = data[0]
for d in data:
abs_dif = abs(d - prev)
if abs_dif > max_abs_dif:
max_abs_dif = abs_dif
prev = d
return max_abs_dif
import unittest
from array_maximal_adjacent_difference import ArrayMaximalAdjacentDifference
class TestArrayMaximalAdjacentDifference(unittest.TestCase):
def test_1(self):
data = [2, 4, 1, 0]
solution = 3
result = ArrayMaximalAdjacentDifference.array_maximal_adjacent_difference(data)
self.assertEqual(result, solution)
def test_2(self):
data = [1, 1, 1, 1]
solution = 0
result = ArrayMaximalAdjacentDifference.array_maximal_adjacent_difference(data)
self.assertEqual(result, solution)
def test_3(self):
data = [-1, 4, 10, 3, -2]
solution = 7
result = ArrayMaximalAdjacentDifference.array_maximal_adjacent_difference(data)
self.assertEqual(result, solution)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment