Determine if array sum can be halved
by Krishna Ananthi
JavaScript
function canPartition(nums) {
let sum = nums.reduce((a, b) => a + b, 0)
if (sum % 2 !== 0) return false
console.log(sum)
const target = sum / 2
let dp = new Set()
dp.add(0)
// console.log(dp)
for (let i = nums.length - 1; i >= 0; i--) {
const nextDp = new Set()
for (const t of dp) {
if (t + nums[i] === target) {
console.log("match")
return true
}
nextDp.add(t + nums[i])
nextDp.add(t)
}
console.log(nextDp)
dp = nextDp;
console.log("dp", dp)
}
console.log(dp)
return false
}
console.log(canPartition([1, 9, 11, 5]))