Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 7, 2025 15:34
Show Gist options
  • Save tatsuyax25/075892e915333cb1f0bb7b003ca28e54 to your computer and use it in GitHub Desktop.
Save tatsuyax25/075892e915333cb1f0bb7b003ca28e54 to your computer and use it in GitHub Desktop.
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
/**
* Determines if the given array of numbers can be partitioned into two subsets with equal sum.
* @param {number[]} nums - Array of integers
* @return {boolean} - True if the array can be partitioned, otherwise false
*/
var canPartition = function(nums) {
const total = nums.reduce((a, b) => a + b, 0);
// If the total is odd, partitioning into two equal subsets is not possible
if (total % 2 !== 0) return false;
const target = total / 2;
// Use a boolean array for the dynamic programming approach
const dp = new Array(target + 1).fill(false);
dp[0] = true; // Base case: a subset sum of 0 is always possible
// Iterate through each number in the array
for (let num of nums) {
// Traverse the dp array backward to prevent overwriting results
for (let j = target; j >= num; j--) {
dp[j] = dp[j] || dp[j - num];
}
}
// The result is whether the target sum is achievable
return dp[target];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment