Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
Next article icon

Maximum sum of Bitwise XOR of elements with their respective positions in a permutation of size N

Last Updated : 10 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer N, the task for any permutation of size N having elements over the range [0, N - 1], is to calculate the sum of Bitwise XOR of all elements with their respective position.

For Example: For the permutation {3, 4, 2, 1, 0}, sum = (0^3 + 1^4 + 2^2 + 3^1 + 4^0) = 2.

Examples:

Input: N = 3
Output: 6
Explanation: For the permutations {1, 2, 0} and {2, 0, 1}, the sum is 6.

Input: N = 2
Output: 2

Approach: To solve this problem, the idea is to recursion to generate all possible permutations of the integers [0, N - 1] and calculate the score for each one of them and then find the maximum score among all the permutations formed.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include<bits/stdc++.h> using namespace std;  // Function to calculate the score int calcScr(vector<int>arr){    // Stores the possible score for   // the current permutation   int ans = 0;    // Traverse the permutation array   for(int i = 0; i < arr.size(); i++)     ans += (i ^ arr[i]);    // Return the final score   return ans; }  // Function to generate all the possible // permutation and get the max score int getMax(vector<int> arr, int ans, vector<bool> chosen, int N) {    // If arr[] length is equal to N   // process the permutation   if (arr.size() == N){     ans = max(ans, calcScr(arr));     return ans;    }    // Generating the permutations   for (int i = 0; i < N; i++)   {      // If the current element is     // chosen     if(chosen[i])       continue;      // Mark the current element     // as true     chosen[i] = true;     arr.push_back(i);      // Recursively call for next     // possible permutation     ans = getMax(arr, ans, chosen, N);      // Backtracking     chosen[i] = false;     arr.pop_back();   }    // Return the ans   return ans; }  // Driver Code int main() {    int N = 2;    // Stores the permutation   vector<int> arr;    // To display the result   int ans = -1;   vector<bool>chosen(N,false);   ans = getMax(arr, ans, chosen, N);    cout << ans << endl; }  // This code is contributed by bgangwar59. 
Java
// Java program for the above approach import java.util.*; class GFG {  // Function to calculate the score static int calcScr(ArrayList<Integer>arr) {    // Stores the possible score for   // the current permutation   int ans = 0;    // Traverse the permutation array   for(int i = 0; i < arr.size(); i++)     ans += (i ^ arr.get(i));    // Return the final score   return ans; }  // Function to generate all the possible // permutation and get the max score static int getMax(ArrayList<Integer> arr, int ans, ArrayList<Boolean> chosen, int N) {    // If arr[] length is equal to N   // process the permutation   if (arr.size() == N)   {     ans = Math.max(ans, calcScr(arr));     return ans;    }    // Generating the permutations   for (int i = 0; i < N; i++)   {      // If the current element is     // chosen     if(chosen.get(i))       continue;      // Mark the current element     // as true     chosen.set(i, true);     arr.add(i);      // Recursively call for next     // possible permutation     ans = getMax(arr, ans, chosen, N);      // Backtracking     chosen.set(i, false);     arr.remove(arr.size()-1);   }    // Return the ans   return ans; }  // Driver Code public static void main(String[] args) {    int N = 2;    // Stores the permutation   ArrayList<Integer> arr = new ArrayList<Integer>();    // To display the result   int ans = -1;   ArrayList<Boolean> chosen = new ArrayList<Boolean>(Collections.nCopies(N, false));   ans = getMax(arr, ans, chosen, N);    System.out.print(ans +"\n"); } }  // This code is contributed by 29AjayKumar  
Python3
# Python program for the above approach  # Function to generate all the possible # permutation and get the max score def getMax(arr, ans, chosen, N):      # If arr[] length is equal to N     # process the permutation     if len(arr) == N:         ans = max(ans, calcScr(arr))         return ans      # Generating the permutations     for i in range(N):                # If the current element is         # chosen         if chosen[i]:             continue                      # Mark the current element         # as true         chosen[i] = True         arr.append(i)                  # Recursively call for next         # possible permutation         ans = getMax(arr, ans, chosen, N)                  # Backtracking         chosen[i] = False         arr.pop()              # Return the ans     return ans  # Function to calculate the score def calcScr(arr):          # Stores the possible score for     # the current permutation     ans = 0          # Traverse the permutation array     for i in range(len(arr)):         ans += (i ^ arr[i])              # Return the final score     return ans   # Driver Code N = 2  # Stores the permutation arr = []  # To display the result ans = -1  chosen = [False for i in range(N)]  ans = getMax(arr, ans, chosen, N)  print(ans) 
C#
// C# program for the above approach using System; using System.Collections.Generic; public class GFG {    // Function to calculate the score   static int calcScr(List<int>arr)   {      // Stores the possible score for     // the current permutation     int ans = 0;      // Traverse the permutation array     for(int i = 0; i < arr.Count; i++)       ans += (i ^ arr[i]);      // Return the readonly score     return ans;   }    // Function to generate all the possible   // permutation and get the max score   static int getMax(List<int> arr, int ans, List<Boolean> chosen, int N)   {      // If []arr length is equal to N     // process the permutation     if (arr.Count == N)     {       ans = Math.Max(ans, calcScr(arr));       return ans;      }      // Generating the permutations     for (int i = 0; i < N; i++)     {        // If the current element is       // chosen       if(chosen[i])         continue;        // Mark the current element       // as true       chosen[i] = true;       arr.Add(i);        // Recursively call for next       // possible permutation       ans = getMax(arr, ans, chosen, N);        // Backtracking       chosen[i] = false;       arr.Remove(arr.Count-1);     }      // Return the ans     return ans;   }    // Driver Code   public static void Main(String[] args)   {      int N = 2;      // Stores the permutation     List<int> arr = new List<int>();      // To display the result     int ans = -1;     List<bool> chosen = new List<bool>(N);     for(int i = 0; i < N; i++)       chosen.Add(false);     ans = getMax(arr, ans, chosen, N);      Console.Write(ans +"\n");   } }  // This code is contributed by shikhasingrajput  
JavaScript
<script>  // JavaScript program for the above approach   // Function to calculate the score function calcScr(arr) {      // Stores the possible score for     // the current permutation     let ans = 0;      // Traverse the permutation array     for (let i = 0; i < arr.length; i++)         ans += (i ^ arr[i]);      // Return the final score     return ans; }  // Function to generate all the possible // permutation and get the max score function getMax(arr, ans, chosen, N) {      // If arr[] length is equal to N     // process the permutation     if (arr.length == N) {         ans = Math.max(ans, calcScr(arr));         return ans;      }      // Generating the permutations     for (let i = 0; i < N; i++) {          // If the current element is         // chosen         if (chosen[i])             continue;          // Mark the current element         // as true         chosen[i] = true;         arr.push(i);          // Recursively call for next         // possible permutation         ans = getMax(arr, ans, chosen, N);          // Backtracking         chosen[i] = false;         arr.pop();     }      // Return the ans     return ans; }  // Driver Code   let N = 2;  // Stores the permutation let arr = [];  // To display the result let ans = -1; let chosen = new Array(N).fill(false); ans = getMax(arr, ans, chosen, N);  document.write(ans + "<br>");   // This code is contributed by gfgking  </script> 

Output: 
2

 

Time Complexity: O(N*N!)
Auxiliary Space: O(N)


Next Article
Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
author
rohitsingh07052
Improve
Article Tags :
  • Bit Magic
  • Mathematical
  • Competitive Programming
  • DSA
  • Arrays
  • permutation
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Bit Magic
  • Mathematical
  • permutation

Similar Reads

  • Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
    Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR of Bitwise OR of every subarray after splitting the array into subarrays(possible zero subarrays). Examples: Input: arr[] = {1, 5, 7}, N = 3Output: 7Explanation:The given array can be expressed as the 1 subarr
    9 min read
  • Maximum sum of Bitwise XOR of all elements of two equal length subsets
    Given an array arr[] of N integers, where N is an even number. The task is to divide the given N integers into two equal subsets such that the sum of Bitwise XOR of all elements of two subsets is maximum. Examples: Input: N= 4, arr[] = {1, 2, 3, 4} Output: 10 Explanation:There are 3 ways possible: (
    14 min read
  • Maximize total set bits of elements in N sized Array with sum M
    Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
    8 min read
  • Maximize sum of XOR of each element of Array with partition number
    Given an array arr of positive integers of size N, the task is to split the array into 3 partitions, such that the sum of bitwise XOR of each element of the array with its partition number is maximum. Examples: Input: arr[] = { 2, 4, 7, 1, 8, 7, 2 }Output: First partition: 2 4 7 1 8Second partition:
    9 min read
  • Count permutations of 0 to N-1 with at least K elements same as positions
    Given two integers, N and K, the task is to find the number of permutations of numbers from 0 to N - 1, such that there are at least K positions in the array such that arr[i] = i ( 0 <= i < N ). As the answer can be very large, calculate the result modulo 10^9+7. Examples: Input: N = 4, K = 3
    15+ min read
  • Count of permutations with minimum possible maximum XOR of adjacent pairs
    Given an integer N, consider an array having elements in the range [0, N-1] such that the maximum Bitwise XOR of all adjacent pairs is minimum out of all possible permutations of the array. Find the number of such permutations. Examples: Input: N = 3Output: 2Explanation: A[] = {2, 0, 1}, Maximum of
    8 min read
  • Generate a permutation of [0, N-1] with maximum adjacent XOR which is minimum among other permutations
    Given an integer N, the task is to print a permutation of numbers from 0 to N-1, such that: There is no duplicate element in the permutationThe maximum adjacent XOR of this permutation is minimum among other permutationsThere can be more than one permutation present that satisfies these conditions.
    6 min read
  • Find an N-length permutation that contains subarrays with sum less than Bitwise XOR
    Given a positive integer N, the task is to find a permutation of length N having Bitwise OR of any of its subarray greater than or equal to the length of the subarray. Examples: Input: N = 5 Output: 1 3 5 2 4 Explanation: Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}. Length o
    3 min read
  • Replace every element of the array with BitWise XOR of all other
    Given an array of integers. The task is to replace every element by the bitwise xor of all other elements of the array. Examples: Input: arr[] = { 2, 3, 3, 5, 5 } Output: 0 1 1 7 7 Bitwise Xor of 3, 3, 5, 5 = 0 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 3, 5 = 7
    5 min read
  • Maximize product of integers formed by splitting digits of N into two parts in any permutation
    Given an integer N in the range [0, 109], the task is to find the maximum product of two integers that are formed by dividing any permutation of digits of integer N into two parts. Example: Input: N = 123Output: 63Explanation: The number of ways of dividing N = 123 into 2 integers are {12, 3}, {21,
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences