Viết hàm nhận mảng số, trả về mảng con 2 phần tử liền kề có tổng gần 0 nhất. Nếu mảng < 2 phần tử, trả về nguyên mảng.
Ví dụ: [4, 4, 12, 3, 3, 1, 5, -4, 2, 2] → [5, -4] (tổng = 1).
Ví dụ
Mã thực hiện:
const arr = [4, 4, 12, 3, 3, 1, 5, -4, 2, 2];
const closestElements = (arr, sum) => {
if(arr.length <= 2){
return arr;
}
const creds = arr.reduce((acc, val, ind) => {
let { closest, startIndex } = acc;
const next = arr[ind+1];
if(!next){
return acc;
}
const diff = Math.abs(sum - (val + next));
if(diff < closest){
startIndex = ind;
closest = diff;
};
return { startIndex, closest };
}, {
closest: Infinity,
startIndex: -1
});
const { startIndex: s } = creds;
return [arr[s], arr[s+1]];
};
console.log(closestElements(arr, 1));
Kết quả
Kết quả in ra console:
[5, -4]