Last active
November 12, 2017 23:16
-
-
Save laras126/416e44ca6196a9eabbb8ab3be440fdf0 to your computer and use it in GitHub Desktop.
Calculating max diff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findDifference = (a, b) => { | |
let diff = a - b; | |
return diff; | |
} | |
const findMaxDifference = (arr) => { | |
let diff = 0, | |
max_diff = 0, | |
min = array[0], | |
max = array[1]; | |
for (let i = 0; i < arr.length; i++) { | |
let diff = findDifference(min, arr[i]); | |
if(arr[i] < min) { | |
min = arr[i]; | |
diff = findDifference(min, arr[i]); | |
} | |
let adjustedDiff = (diff) => { | |
if (diff < 0) { | |
diff = diff * -1; | |
} | |
return diff; | |
}; | |
if(adjustedDiff(diff) > max_diff) { | |
max_diff = diff; | |
max = arr[i]; | |
} | |
} | |
return `min is ${min}, max is ${max}, diff ${diff}, max diff is ${max_diff}`; | |
}; | |
const array = [40, -20, 4, 9, 30, 15, 3, 1, 10]; // min is -20, max is 30, diff 0, max diff is 50 | |
console.log(findMaxDifference(array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment