Can anyone reduce time complexity of this code

51 Views Asked by At

You are given three integers A, B, and C. You are allowed to perform the following operation any number of times (possibly zero). • Choose any integer X such that X ≤ max (A,B, C), and replace A with A^X, B with B^X, and C with C^X. Here denote Bitwise XOR operation. Find the maximum possible value of A+B+C.

A=2
B=2
C=2
def maxSum(a,b,c):
    list=[]
    l=[a,b,c]
    l.sort()
    if a==b==c:
        for x in range(int(a/2),l[-1]):
            new=((a^x)+(b^x)+(c^x))
            list.append(new)
        return list[-1]
    else:
        for x in range(l[1],l[-1]):
            new=((a^x)+(b^x)+(c^x))
            list.append(new)
        return list[-1]
maximum=maxSum(A,B,C)
print(maximum)

How to make the code run faster?

I tried using for loop but the runtime was so much. I want to know how to reduce runtime. What are the modifications needed.

1

There are 1 best solutions below

0
Riccardo Bucco On

Try this:

def max_sum(a, b, c):
    for j in range(int.bit_length(max(a, b, c))):
        x = 2**j if sum((n & 2**j) >> j for n in (a, b, c)) < 2 else 0
        a = a ^ x
        b = b ^ x
        c = c ^ x
    return a + b + c

So here you perform a number of operations equal to the number of bits of the largest number. x is either a power of 2 or 0.

Example:

>>> max_sum(8, 3, 5)
30