Skip to content

Commit c9ed1ba

Browse files
clojure: partition equal subset sum
1 parent 7bb0b89 commit c9ed1ba

File tree

1 file changed

+55
-0
lines changed
  • clojure/algorithms/others/partition-equal-subset-sum-april-8-2024

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
(ns core
2+
(:require [clojure.test :refer [deftest is testing]]))
3+
4+
(comment
5+
"Given an integer array nums, return true if
6+
you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
7+
8+
Example 1:
9+
10+
Input: nums = [1,5,11,5]
11+
Output: true
12+
Explanation: The array can be partitioned as [1, 5, 5] and [11].
13+
Example 2:
14+
15+
Input: nums = [1,2,3,5]
16+
Output: false
17+
Explanation: The array cannot be partitioned into equal sum subsets.
18+
19+
20+
Constraints:
21+
22+
1 <= nums.length <= 200
23+
1 <= nums[i] <= 100")
24+
25+
;; time O(n * sum(nums))
26+
;; space O(sum(nums))
27+
(defn can-partition [nums]
28+
;; O(n)
29+
(let [sum (reduce + nums)
30+
half (/ sum 2)]
31+
(if (odd? sum)
32+
false
33+
;; O(n)
34+
(let [result (reduce (fn [seen num]
35+
;; O(sum(nums))
36+
(let [new-seen (reduce (fn [new-seen other-num] (let [total (+ num other-num)]
37+
(if (<= half total)
38+
(conj new-seen total)
39+
new-seen)))
40+
seen
41+
seen)]
42+
(if (contains? new-seen half)
43+
(reduced true)
44+
new-seen)))
45+
#{0}
46+
nums)]
47+
(= result true)))))
48+
49+
(deftest can-partition-test
50+
(testing "example 1"
51+
(is (= true (can-partition '(1 5 11 5))))
52+
(is (= false (can-partition '(1 2 3 5))))
53+
(is (= true (can-partition '(1 1))))))
54+
55+
(clojure.test/run-all-tests)

0 commit comments

Comments
 (0)