Hi all I need to return the minimum possible absolute difference. My code is below,
function minAbsDiff(nums) {
const n = nums.length;
const sum = nums.reduce((acc, val) => acc + val);
const halfSum = Math.floor(sum / 2);
const dp = Array.from({ length: n+1 }, () => Array.from({ length: sum+1 }, () => false));
dp[0][0] = true;
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= sum; j++) {
dp[i][j] = dp[i-1][j] || (j >= nums[i-1] ? dp[i-1][j-nums[i-1]] : false);
}
}
let j = halfSum;
while (!dp[n][j]) j--;
console.log(sum - 2*j);
}
var x = [2,-1,0,4,-2,-9];
minAbsDiff(x);
Here if I give the above x value I got an error:
RangeError: Potential infinite loop: exceeded 1500 iterations
Other than the above value, I got the result. Help me clear this error.
I tried giving other array values it working fine except the
var x = [2,-1,0,4,-2,-9];
I need to get difference for it.