Untitled
user_0606344
python
a year ago
1.0 kB
9
Indexable
def subsetSum(A, k):
n = len(A)
# Calculate the total sum range considering both positive and negative numbers
sum_min = sum(x for x in A if x < 0)
sum_max = sum(x for x in A if x > 0)
# DP table: Use a dictionary to handle possible negative indices
T = [{} for _ in range(n + 1)]
# Base case: There's always a subset with sum 0 (empty subset)
T[0][0] = True
# Fill the DP table
for i in range(1, n + 1):
for current_sum in range(sum_min, sum_max + 1):
if current_sum in T[i - 1]:
# Case 1: Exclude the current element
T[i][current_sum] = T[i - 1][current_sum]
# Case 2: Include the current element
new_sum = current_sum + A[i - 1]
T[i][new_sum] = True
# Return whether a subset with sum `k` exists
return T[n].get(k, False)
# Test case
A = [12, 1, 61, 5, 9, -3, -1]
k = 72
print(subsetSum(A, k)) # Should return True or False based on the subsetEditor is loading...
Leave a Comment