
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Subsequences with Maximum Bitwise AND and Bitwise OR in Python
Suppose we have an array of n elements, we have to show the maximum sum by choosing two subsequences of the array (they may or may not be different) so that the sum of bit-wise AND operation of all elements of the first subsequence and bit-wise OR operation of all the elements of the second subsequence is maximum.
So, if the input is like A = {4, 6, 7, 2}, then the output will be 14 as we are getting maximum AND value by selecting 7 only and maximum OR value by selecting all (4 | 6 | 7 | 2) = 7. So, the result will be 7 + 7 = 14.
To solve this, we will follow these steps −
and_max := maximum of arr
or_max := 0
-
for i in range 0 to size of arr, do
or_max := or_max OR arr[i]
return and_max + or_max
Example
Let us see the following implementation to get better understanding −
def get_max_sum(arr): and_max = max(arr) or_max = 0 for i in range(len(arr)): or_max|= arr[i] return and_max + or_max a = [4,6,7,2] print(get_max_sum(a))
Input
[4,6,7,2]
Output
14