JavaScript: Find the maximum difference among all possible pairs of a given array of integers
JavaScript Basic: Exercise-93 with Solution
Find Max Difference Among All Pairs in Array
Write a JavaScript program to find the maximum difference among all possible pairs of a given array of integers.
Sample Solution:
JavaScript Code:
// Function to find the maximum difference between any two elements in an array
function array_max_diff(arr) {
var max_result = 0; // Initialize the variable to store the maximum difference
// Iterate through the array elements
for(var i = 0; i < arr.length; i++) {
// Iterate through other elements in the array
for(var k = 0; k !== i && k < arr.length; k++) {
var diff = Math.abs(arr[i] - arr[k]); // Calculate the absolute difference
max_result = Math.max(max_result, diff); // Update the maximum difference
}
}
return max_result; // Return the final maximum difference
}
// Example usage
console.log(array_max_diff([1, 2, 3, 8, 9])); // 8
console.log(array_max_diff([1, 2, 3, 18, 9])); // 17
console.log(array_max_diff([13, 2, 3, 8, 9])); // 11
Output:
8 17 11
Live Demo:
See the Pen javascript-basic-exercise-93 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Function to find the maximum difference between elements in an array
const array_max_diff = (arr) => {
let max_result = 0; // Initialize the maximum difference variable
// Iterate through the array to calculate the differences between elements
for (let i = 0; i < arr.length; i++) {
for (let k = 0; k !== i && k < arr.length; k++) {
const diff = Math.abs(arr[i] - arr[k]); // Calculate the absolute difference
max_result = Math.max(max_result, diff); // Update the maximum difference
}
}
return max_result; // Return the final maximum difference
};
// Example usage
console.log(array_max_diff([1, 2, 3, 8, 9])); // 8
console.log(array_max_diff([1, 2, 3, 18, 9])); // 17
console.log(array_max_diff([13, 2, 3, 8, 9])); // 11
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to find the maximum difference between any two adjacent elements of a given array of integers.
Next: JavaScript program to find the number which appears most in a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-93.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics