File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ '''
2+ Count Positives
3+
4+ Given several numbers, count how many different results bigger or equal than 0 can you produce by only
5+ using addition (+) and substraction (-). All the numbers must be used.
6+
7+ Input: [2, 3, 1]
8+ Output: 4
9+ Output explanation:
10+ 2+3+1 = 6
11+ 2+3-1 = 4
12+ 2-3+1 = 0
13+ 2-3-1 = -2 (negative)
14+ -2+3+1 = 2
15+ -2+3-1 = 0 (double)
16+ -2-3+1 = -4 (negative)
17+ -2-3-1 = - 6 (negative)
18+
19+ =========================================
20+ Use hashset and make all combinations.
21+ Time Complexity: O(2^N) , I'm not sure how to compute the real complexity, but it's TOO MUCH faster than 2^N
22+ Space Complexity: O(2^N)
23+ '''
24+
25+
26+ ############
27+ # Solution #
28+ ############
29+
30+ def count_positives (numbers ):
31+ results = set ()
32+ results .add (0 )
33+
34+ # make all combinations
35+ for num in numbers :
36+ temp = set () # use a temporary hashset for the newest results
37+ for res in results :
38+ temp .add (res + num )
39+ temp .add (res - num )
40+ results = temp # replace the results
41+
42+ # count unique positives
43+ count = 0
44+ for res in results :
45+ if res >= 0 :
46+ count += 1
47+
48+ return count
49+
50+
51+ ###########
52+ # Testing #
53+ ###########
54+
55+ # Test 1
56+ # Correct result => 4
57+ print (count_positives ([2 , 3 , 1 ]))
You can’t perform that action at this time.
0 commit comments