Max XOR sum
Last Updated :
11 Apr, 2023
Given four integers A, B, C, and D, the task is to find the maximum sum of the given numbers by using the below operations any number of times.
- Calculate X = A ^ B, and replace A or B with X
- Calculate Y = C ^ D, and replace C or D with Y.
Examples:
Input: arr[] = {4, 5, 9, 12}
Output: 30
Explanation: X = 4 ^ 5 = 1
Y = 9 ^ 12 = 5 replace A with X and D with Y
X = 1 ^ 5 = 4
Y = 9 ^ 5 = 12 replace A with X and D with Y
Now, A + B + C + D = 30, it can be proved that this is the maximum sum that can be obtained
Input: arr[] = {0, 1, 0, 1}
Output: 4
Explanation: X = 0 ^ 1 = 1
Y = 1 ^ 0 = 1 replace A with X and C with Y
Now, A + B + C + D = 4, It can be proved that this is the maximum sum that can be proved.
Approach: This can be solved with the following idea:
This can be solved by some mathematical operations.
Below are the steps of implementation:
- Calculate the XOR of A and B, C and D.
- See maximum of (A + B), ( A + X), and (B + X).
- Similarly for C and D.
- Return the sum of the maximums found above.
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxSumXor( int A, int B, int C, int D)
{
int X = A ^ B;
int Y = C ^ D;
int fpos = max(A + B, max(A + X, X + B));
int spos = max(C + D, max(C + Y, Y + D));
int ans = fpos + spos;
return ans;
}
int main()
{
int a = 4, b = 5, c = 9, d = 12;
cout << maxSumXor(a, b, c, d);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int maxSumXor( int A, int B, int C, int D)
{
int X = A ^ B;
int Y = C ^ D;
int fpos = Math.max(A + B, Math.max(A + X, X + B));
int spos = Math.max(C + D, Math.max(C + Y, Y + D));
int ans = fpos + spos;
return ans;
}
public static void main(String[] args)
{
int a = 4 , b = 5 , c = 9 , d = 12 ;
System.out.println(maxSumXor(a, b, c, d));
}
}
|
Python3
def maxSumXor(A, B, C, D):
X = A ^ B
Y = C ^ D
fpos = max (A + B, max (A + X, X + B))
spos = max (C + D, max (C + Y, Y + D))
ans = fpos + spos
return ans
a, b, c, d = 4 , 5 , 9 , 12
print (maxSumXor(a, b, c, d))
|
C#
using System;
class GFG {
static int maxSumXor( int A, int B, int C, int D)
{
int X = A ^ B;
int Y = C ^ D;
int fpos = Math.Max(A + B, Math.Max(A + X, X + B));
int spos = Math.Max(C + D, Math.Max(C + Y, Y + D));
int ans = fpos + spos;
return ans;
}
public static void Main()
{
int a = 4, b = 5, c = 9, d = 12;
Console.Write(maxSumXor(a, b, c, d));
}
}
|
Javascript
<script>
function maxSumXor(A, B, C, D) {
let X = A ^ B;
let Y = C ^ D;
let fpos = Math.max(A + B, Math.max(A + X, X + B));
let spos = Math.max(C + D, Math.max(C + Y, Y + D));
let ans = fpos + spos;
return ans;
}
let a = 4,
b = 5,
c = 9,
d = 12;
console.log(maxSumXor(a, b, c, d));
</script>
|
Time Complexity: O(1)
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...