-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathminimumAbsoluteDifference.js
More file actions
34 lines (24 loc) · 812 Bytes
/
minimumAbsoluteDifference.js
File metadata and controls
34 lines (24 loc) · 812 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @link Problem definition [[docs/hackerrank/implementation/minimumAbsoluteDifference.md]]
*/
import { logger as console } from '../../logger.js';
function minimumAbsoluteDifference(arr) {
if (arr.length === 0) {
throw new Error('Empty input');
}
const sortedNums = [...arr].sort((a, b) => a - b);
console.log(`sortedNums: ${sortedNums}`);
let result = Math.abs(sortedNums[0] - sortedNums[1]);
for (let i = 0; i < sortedNums.length - 1; i++) {
const a = sortedNums[i];
const b = sortedNums[i + 1];
const diff = Math.abs(a - b);
console.debug(
`(i: ${i}, i+1: ${i + 1}) => |a - b| = |${a} - ${b}| = ${diff}`
);
result = Math.min(result, diff);
}
return result;
}
export default { minimumAbsoluteDifference };
export { minimumAbsoluteDifference };