# Maximum difference between a number JavaScript

In this problem statement, our task is to write the function for finding the maximum difference between a number in an array with the usage of Javascript functionalities. So we will use a nested loop to get the difference between two numbers.

## Understanding the problem statement

The above problem statement is saying to find the maximum difference between any two numbers in the given array of integer numbers. In simple terms we have to find the largest possible difference between any two numbers of the array in which the larger number appears after the smaller number. Suppose we have an array [2, 3, 5, 6, 4, 1], so the maximum difference between 6 and 1 is 5.

## Logic for the above problem

For solving the given problem we have to find an effective algorithm which can handle arrays of different sizes. In the algorithm we will work by iterating through the array for one time and keep track of the minimum value found and the maximum difference is seen. So overall the problem is asking us to get an efficient way to calculate the maximum difference between any two numbers in an array.

## Algorithm

Step 1 − Create a function to get the maximum difference between two numbers in an array.

Step 2 − Check the length of the given array if the length is less than two then stop the execution because difference is not possible.

Step 3 − If the above condition is false then proceed further by calculating the difference between first and second item of the array and store it in a variable.

Step 4 − Now we have the difference of first two numbers then with the help of nested for loops we will check the conditions if the current difference is greater than the previous difference then add current difference to the max difference.

Step 5 − After iterating all the items of the array we will have the maximum difference of two items.

## Code for the algorithm

//Define a function to find maximum difference between two numbers
function maxDiff(array) {
if (array.length < 2) {
return null;
}
var maxDifference = array[1] - array[0];
for (var n = 0; n < array.length - 1; n++) {
for (var m = n + 1; m < array.length; m++) {
if (array[m] - array[n] > maxDifference) {
maxDifference = array[m] - array[n];
}
}
}
return maxDifference;
}
console.log("Maximum difference between any two elements:");
console.log(maxDiff([3, 5, 6, 2, 7, 4]));


## Complexity

The time complexity for the implemented algorithm is O(n^2) because we have used two nested for loops in our code. And here n is the number of items in the given array.

## Conclusion

This is how we can solve the above problem statement by taking appropriate logic. As we have used two nested for loops so the complexity is O(n^2) which is not good for large sized arrays.

Updated on: 18-May-2023

77 Views

##### Kickstart Your Career

Get certified by completing the course