We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 954adff commit 6c5274aCopy full SHA for 6c5274a
dynamic-programming/partition-equal-subset-sum.js
@@ -0,0 +1,25 @@
1
+// Given a non-empty array nums containing only positive integers,
2
+// find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
3
+var canPartition = function (nums) {
4
+ if (!nums) return false;
5
+ let total = nums.reduce((a, b) => a + b, 0);
6
+
7
+ if (total % 2 != 0) return false;
8
9
+ let target = total / 2;
10
+ let arr = new Array(target + 1).fill(false);
11
+ arr[0] = true;
12
13
+ for (let el of nums) {
14
+ for (let i = target; i >= 0; i--) {
15
+ let complement = i - el;
16
17
+ if (!arr[i] && arr[complement]) {
18
+ arr[i] = true;
19
+ }
20
+ if (arr[target] == true) return true;
21
22
23
24
+ return false;
25
+};
0 commit comments