Skip to content

Commit 33e9a39

Browse files
author
Мето Трајковски
committed
Added solution for count_positives
1 parent b5e5bce commit 33e9a39

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

Other/count_positives.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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]))

0 commit comments

Comments
 (0)