How To Get The Elements With Maximum Difference In The Single Array?
Suppose, a= [3,7, 8,66,121,223,228] how to get the elements with maximum difference among them? I have this solution to it but will appreciate better code than this. let arr = [] a
Solution 1:
You could check each pair with the last found pair and get the one with the greatest delta.
var array = [3, 7, 8, 66, 121, 223, 228],
result = array.reduce((r, b, i, { [i - 1]: a }) => {
if (i === 0) return;
if (i === 1 || b - a > r[1] - r[0]) return [a, b];
return r;
}, undefined);
console.log(result);
Solution 2:
You can do this
var a = [3,7, 8,66,121,223,228]
var difference = 0;
var pairIndex = 0;
for(i = 0; i < a.length; i++) {
var currentItem = a[i];
var nextItem = a[i+1];
var currentDifference = Math.abs(currentItem - nextItem);
if(currentDifference > difference) {
difference = currentDifference;
pairIndex = i;
}
}
var pair = [a[pairIndex], a[pairIndex + 1]];
return pair;
Solution 3:
a= [3,7, 8,66,121,223,228]
letMaxIntervalPosition = 0for(let i=0;i<a.length-2;i++){
if(Math.abs(a[i]-a[i+1]) > MaxIntervalPosition) {
MaxIntervalPosition = i
}
return [a[i],a[i+1]]
}
Solution 4:
The code below returns 3 elements
0 - The max difference found
1 - Element 1 of the pair.
2 - Element 2 of the pair.
using a reduce
statement to iterate and find the pair is fairly simple.
I have not tested this with randomized array.
const array = [3,7, 8,66,121,223,228];
constmaxDiff = (arr) => arr.reduce((a, v, i) =>
{
if(i === arr.length-1) return a;
const diff = Math.abs(v-arr[i+1]);
return (diff > a[0]) ? [diff, v, arr[i+1]] : a;
}, [0]);
console.log(maxDiff(array));
// use a simple destructure to seperate diff and elementsconst [diff, ...elements] = maxDiff(array);
console.log(elements);
Solution 5:
You can solve this in a concise way with Array.reduce:
letmaxDiff = arr => arr.reduce((acc, c, i, arr) => {
if(i && c - arr[i-1] > arr[i-1] - arr[i-2])
acc = [arr[i-1], c]
return acc
}, [])
console.log(maxDiff([3,7,8,66,121,223,228])) // <-- [121,223]console.log(maxDiff([3,7,8,66,121,223,228,1000])) // <-- [228,1000]
The idea is to start from the first element (i == 1)
and from there compare the difference between the last pair arr[i-1] - arr[i-2]
and the current pair (c - arr[i-1])
. If the difference is bigger overwrite the accumulator until you reach the end.
You can actually one line it via:
letmaxDiff = arr => arr.reduce((r,c,i,a) =>
(r = i && c - a[i-1] > a[i-1] - (a[i-2] || 0) ? [a[i-1], c] : r, r), [])
console.log(maxDiff([3,7,8,66,121,223,228])) // <-- [121,223]console.log(maxDiff([3,7,8,66,121,223,228,1000])) // <-- [228,1000]
Post a Comment for "How To Get The Elements With Maximum Difference In The Single Array?"