有两个数组a和b问b的哪一段之和和a最接近给我js代码
function findClosestSum(a, b) { let minDiff = Infinity; let closestSum = 0; for (let i = 0; i < b.length; i++) { for (let j = i; j < b.length; j++) { const sum = b.slice(i, j + 1).reduce((acc, cur) => acc + cur, 0); const diff = Math.abs(sum - a); if (diff < minDiff) { minDiff = diff; closestSum = sum; } } } return closestSum; }
// Example usage: const a = 10; const b = [1, 2, 3, 4, 5]; console.log(findClosestSum(a, b)); // Output: 10 (b[0] + b[1] + b[2])
原文地址: https://www.cveoy.top/t/topic/bKiB 著作权归作者所有。请勿转载和采集!