Created
May 9, 2023 02:50
-
-
Save debedb/7dd1d6155cfaeee665dce8ecbac4c95a to your computer and use it in GitHub Desktop.
Find subarrays with equal sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def findEqualParts(remArr, half, s, d=0): | |
for i in range(len(remArr)): | |
remArr2 = remArr[:] | |
diff = s - remArr2[i] | |
# print(f"Entering findEqualParts({remArr}, {half}, {s}; diff is {diff}, i is {i}, d is {d}") | |
if diff > 0: | |
half2 = half[:] | |
half2.append(remArr2[i]) | |
s2 = s - remArr[i] | |
del remArr2[i] | |
retval = findEqualParts(remArr2, half2, s2, d+1) | |
if retval == -1: | |
continue | |
return retval | |
if diff == 0: | |
half2 = half[:] | |
half2.append(remArr2[i]) | |
del remArr2[i] | |
if sum(half2) == sum(remArr2): | |
return (half2, remArr2) | |
continue | |
if diff < 0: | |
continue | |
return -1 | |
def ArrayChallenge(arr): | |
arr.sort(reverse=True) | |
# print(f"Sorted {arr}") | |
s = sum(arr)//2 | |
(half1, half2) = findEqualParts(arr, [], s) | |
half1.sort() | |
half2.sort() | |
# print(sum(half1)) | |
# print(sum(half2)) | |
arr = half1 + half2 | |
return ",".join([str(x) for x in arr]) | |
arr = [16, 22, 35, 8, 20, 1, 21, 11] | |
print(ArrayChallenge(arr)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment