Solutions for Sum Closest to 0

    • @GarretVam
    • @mason, submitted in Python 2, achived 100% score
    def solve(arr):
        arr_size = len(arr)
        nv_count = 0
        if arr_size < 2:
            return 'Invalid Input'
        min_l = 0
        min_r = 1
        min_sum = arr[0] + arr[1]
        for l in range(0, arr_size - 1):
            for r in range(l + 1, arr_size):
                sum = arr[l] + arr[r]
                if abs(min_sum) > abs(sum):
                    min_sum = sum
                    min_l = l
                    min_r = r
        return (arr[min_l], arr[min_r])
    • @GarretVam
    • @mason, submitted in Python 3, achived 100% score
    def solve(arr):
        arr_size = len(arr)
        nv_count = 0
        if arr_size < 2:
            return 'Invalid Input'
        min_l = 0
        min_r = 1
        min_sum = arr[0] + arr[1]
        for l in range(0, arr_size - 1):
            for r in range(l + 1, arr_size):
                sum = arr[l] + arr[r]
                if abs(min_sum) > abs(sum):
                    min_sum = sum
                    min_l = l
                    min_r = r
        return (arr[min_l], arr[min_r])
    • @GarretVam
    • @mason, submitted in Python 3, achived 100% score
    def solve(arr):
        arr_size = len(arr)
        nv_count = 0
        if arr_size < 2:
            return 'Invalid Input'
        min_l = 0
        min_r = 1
        min_sum = arr[0] + arr[1]
        for l in range(0, arr_size - 1):
            for r in range(l + 1, arr_size):
                sum = arr[l] + arr[r]
                if abs(min_sum) > abs(sum):
                    min_sum = sum
                    min_l = l
                    min_r = r
        return (arr[min_l], arr[min_r])