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:
Maximum Sum Subsequence of length k
Next article icon

Maximum bitwise OR value of subsequence of length K

Last Updated : 07 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of n positive integers and an integer k, the task is to find the maximum value of the bitwise OR of any subsequence of size k.

Examples: 

Input: arr[] = [2, 5, 3, 6, 11, 13], k = 3 
Output: 15 
Explanation: The sub-sequence with maximum OR value is [2, 11, 13].

Input: arr[] = [5, 9, 7, 19], k = 3 
Output: 31 
Explanation: The sub-sequence with maximum OR value is [5, 9, 19].

Table of Content

  • Using Recursion – O(2^n) Time and O(n) Space
  • Using Dynamic Programming – O(n*k*maxOR) Time and O(n*k*maxOR) Space

Using Recursion – O(2^n) Time and O(n) Space

The idea is to use recursion to explore all possible subsequences of size k. By either including or excluding each element at a given index, we can generate all combinations. The key is to calculate the bitwise OR for each valid subsequence and return the maximum OR value among them.

The recursive relation will be –

  • include = maxOrHelper(arr, n, k, index + 1, currOR | arr[index], currSize + 1)
  • exclude = maxOrHelper(arr, n, k, index + 1, currOR, currSize);

The final result will me the max(include, exclude).

C++
// C++ implementation to find Max OR of // subsequence of size k using Recursion #include <bits/stdc++.h> using namespace std;  // Helper function to calculate the maximum OR  // of subsequences of size k int maxOrHelper(vector<int>&arr, int n,                 int k, int index, int currOR,                                    int currSize) {        // If we have selected k elements, return     // the current OR value     if (currSize == k) {         return currOR;     }          // If we have exhausted all elements     if (index == n) {         return 0;     }          // Include the current element and recurse     int include = maxOrHelper(arr, n, k, index + 1,                        currOR | arr[index], currSize + 1);          // Skip the current element and recurse     int exclude = maxOrHelper(arr, n, k, index + 1,                                       currOR, currSize);          // Return the maximum of including or      // excluding the current element     return max(include, exclude); }  int maxOrK(vector<int>& arr, int k) {     int n = arr.size();     return maxOrHelper(arr, n, k, 0, 0, 0); }  int main() {        vector<int> arr = {2, 5, 3, 6, 11, 13};     int k = 3;     cout << maxOrK(arr, k);      return 0; } 
Java
// Java implementation to find Max OR of // subsequence of size k using Recursion import java.util.*;  class GfG {      // Helper function to calculate the maximum OR      // of subsequences of size k     static int maxOrHelper(List<Integer> arr, int n,                             int k, int index, int currOR,                             int currSize) {            // If we have selected k elements, return         // the current OR value         if (currSize == k) {             return currOR;         }              // If we have exhausted all elements         if (index == n) {             return 0;         }              // Include the current element and recurse         int include = maxOrHelper(arr, n, k, index + 1,                          currOR | arr.get(index), currSize + 1);              // Skip the current element and recurse         int exclude = maxOrHelper(arr, n, k, index + 1,                                    currOR, currSize);              // Return the maximum of including or          // excluding the current element         return Math.max(include, exclude);     }      static int maxOrK(List<Integer> arr, int k) {         int n = arr.size();         return maxOrHelper(arr, n, k, 0, 0, 0);     }      public static void main(String[] args) {            List<Integer> arr             = Arrays.asList(2, 5, 3, 6, 11, 13);                int k = 3;         System.out.println(maxOrK(arr, k));      } } 
Python
# Python implementation to find Max OR of # subsequence of size k using Recursion  # Helper function to calculate the maximum OR  # of subsequences of size k def maxOrHelper(arr, n, k, index, currOR, currSize):      # If we have selected k elements, return     # the current OR value     if currSize == k:         return currOR          # If we have exhausted all elements     if index == n:         return 0          # Include the current element and recurse     include = maxOrHelper(arr, n, k, index + 1,\                    currOR | arr[index], currSize + 1)          # Skip the current element and recurse     exclude = maxOrHelper(arr, n, k,\                          index + 1, currOR, currSize)          # Return the maximum of including or      # excluding the current element     return max(include, exclude)  def maxOrK(arr, k):     n = len(arr)     return maxOrHelper(arr, n, k, 0, 0, 0)  if __name__ == "__main__":      arr = [2, 5, 3, 6, 11, 13]     k = 3     print(maxOrK(arr, k)) 
C#
// C# implementation to find Max OR of // subsequence of size k using Recursion using System; using System.Collections.Generic;  class GfG {      // Helper function to calculate the maximum OR      // of subsequences of size k     static int maxOrHelper(List<int> arr, int n,                             int k, int index, int currOR,                             int currSize) {            // If we have selected k elements, return         // the current OR value         if (currSize == k) {             return currOR;         }              // If we have exhausted all elements         if (index == n) {             return 0;         }              // Include the current element and recurse         int include = maxOrHelper(arr, n, k, index + 1,                           currOR | arr[index], currSize + 1);              // Skip the current element and recurse         int exclude = maxOrHelper(arr, n, k, index + 1,                                    currOR, currSize);              // Return the maximum of including or          // excluding the current element         return Math.Max(include, exclude);     }      static int maxOrK(List<int> arr, int k) {         int n = arr.Count;         return maxOrHelper(arr, n, k, 0, 0, 0);     }      static void Main(string[] args) {            List<int> arr               = new List<int> { 2, 5, 3, 6, 11, 13 };          int k = 3;           Console.WriteLine(maxOrK(arr, k));      } } 
JavaScript
// JavaScript implementation to find Max OR of // subsequence of size k using Recursion  // Helper function to calculate the maximum OR  // of subsequences of size k function maxOrHelper(arr, n, k, index,                             currOR, currSize) {      // If we have selected k elements, return     // the current OR value     if (currSize === k) {         return currOR;     }      // If we have exhausted all elements     if (index === n) {         return 0;     }      // Include the current element and recurse     let include = maxOrHelper(arr, n, k, index + 1,                    currOR | arr[index], currSize + 1);      // Skip the current element and recurse     let exclude = maxOrHelper(arr, n, k, index + 1,                                   currOR, currSize);      // Return the maximum of including or      // excluding the current element     return Math.max(include, exclude); }  function maxOrK(arr, k) {     let n = arr.length;     return maxOrHelper(arr, n, k, 0, 0, 0); }  let arr = [2, 5, 3, 6, 11, 13]; let k = 3; console.log(maxOrK(arr, k)); 

Output
15

Using Dynamic Programming – O(n*k*maxOR) Time and O(n*k*maxOR) Space

The idea is to optimize the recursive solution by using memoization to avoid redundant computations. Instead of recalculating the maximum OR value for the same state (defined by the index, current OR value, and size of the subsequence), we store the results in a 3D memoization table with dimensions [n][k+1][maxPossibleOR+1]. and fill it with -1. By doing so, the solution ensures each state is computed only once, significantly reducing the overall computational complexity.

C++
// C++ implementation to find Max OR of // subsequence of size k using Memoization #include <bits/stdc++.h> using namespace std;  // Helper function with memoization int maxOrHelper(vector<int>& arr, int n, int k,                   int index, int currOR, int currSize,                   vector<vector<vector<int>>>& memo) {      // If we have selected k elements, return      // the current OR value     if (currSize == k) {         return currOR;     }      // If we have exhausted all elements     if (index == n) {         return 0;     }      // Check if the result is already computed     if (memo[index][currSize][currOR] != -1) {         return memo[index][currSize][currOR];     }      // Include the current element and recurse     int include = maxOrHelper(arr, n, k, index + 1,                        currOR | arr[index], currSize + 1, memo);      // Skip the current element and recurse     int exclude = maxOrHelper(arr, n, k, index + 1,                                currOR, currSize, memo);      // Store the result in the memoization table     memo[index][currSize][currOR] = max(include, exclude);      return memo[index][currSize][currOR]; }  int MaxOrK(vector<int>& arr, int k) {     int n = arr.size();          // Create a memoization table with dimensions [n][k+1]     // [maximum possible OR value]     int maxPossibleOR = 0;          for (int num : arr) {         maxPossibleOR |= num;     }      // Create a 3D memo table, initializing all values      // as -1     vector<vector<vector<int>>> memo(n + 1,                                  vector<vector<int>>(k + 1,                                  vector<int>(maxPossibleOR + 1, -1)));      return maxOrHelper(arr, n, k, 0, 0, 0, memo); }  int main() {        vector<int> arr = {2, 5, 3, 6, 11, 13};     int k = 3;     cout << MaxOrK(arr, k) << endl;     return 0; } 
Java
// Java implementation to find Max OR of // subsequence of size k using Memoization import java.util.*;  class GfG {      // Helper function with memoization     static int maxOrHelper(List<Integer> arr, int n, int k,                             int index, int currOR, int currSize,                             int[][][] memo) {          // If we have selected k elements, return          // the current OR value         if (currSize == k) {             return currOR;         }          // If we have exhausted all elements         if (index == n) {             return 0;         }          // Check if the result is already computed         if (memo[index][currSize][currOR] != -1) {             return memo[index][currSize][currOR];         }          // Include the current element and recurse         int include = maxOrHelper(arr, n, k, index + 1,                                    currOR | arr.get(index),                                    currSize + 1, memo);          // Skip the current element and recurse         int exclude = maxOrHelper(arr, n, k, index + 1,                                    currOR, currSize, memo);          // Store the result in the memoization table         memo[index][currSize][currOR] = Math.max(include, exclude);          return memo[index][currSize][currOR];     }      static int MaxOrK(List<Integer> arr, int k) {         int n = arr.size();                  // Create a memoization table with dimensions [n][k+1]         // [maximum possible OR value]         int maxPossibleOR = 0;                  for (int num : arr) {             maxPossibleOR |= num;         }          // Create a 3D memo table, initializing all values          // as -1         int[][][] memo = new int[n + 1][k + 1][maxPossibleOR + 1];                  // Initialize the memo table with -1         for (int i = 0; i <= n; i++) {             for (int j = 0; j <= k; j++) {                 Arrays.fill(memo[i][j], -1);             }         }          return maxOrHelper(arr, n, k, 0, 0, 0, memo);     }      public static void main(String[] args) {                List<Integer> arr = Arrays.asList(2, 5, 3, 6, 11, 13);         int k = 3;         System.out.println(MaxOrK(arr, k));     } } 
Python
# Python implementation to find Max OR of # subsequence of size k using Memoization  # Helper function with memoization def maxOrHelper(arr, n, k, index, currOR, currSize, memo):        # If we have selected k elements,      # return the current OR value     if currSize == k:         return currOR      # If we have exhausted all elements     if index == n:         return 0      # Check if the result is already computed     if memo[index][currSize][currOR] != -1:         return memo[index][currSize][currOR]      # Include the current element and recurse     include = maxOrHelper(arr, n, k, index + 1, \                   currOR | arr[index], currSize + 1, memo)      # Skip the current element and recurse     exclude = maxOrHelper(arr, n, k, \                          index + 1, currOR, currSize, memo)      # Store the result in the memoization table     memo[index][currSize][currOR] = max(include, exclude)      return memo[index][currSize][currOR]  def MaxOrK(arr, k):     n = len(arr)          # Create a memoization table with dimensions [n][k+1]     # [maximum possible OR value]     maxPossibleOR = 0          for num in arr:         maxPossibleOR |= num      # Create a 3D memo table, initializing all values      # as -1     memo = [[[ -1 for i in range(maxPossibleOR + 1)] \               for i in range(k + 1)] for i in range(n + 1)]      return maxOrHelper(arr, n, k, 0, 0, 0, memo)  if __name__ == "__main__":      arr = [2, 5, 3, 6, 11, 13]     k = 3     print(MaxOrK(arr, k)) 
C#
// C# implementation to find Max OR of // subsequence of size k using Memoization using System; using System.Collections.Generic;  class GfG {      // Helper function with memoization     static int MaxOrHelper(List<int> arr, int n, int k,                             int index, int currOR, int currSize,                             int[,,] memo) {          // If we have selected k elements, return          // the current OR value         if (currSize == k) {             return currOR;         }          // If we have exhausted all elements         if (index == n) {             return 0;         }          // Check if the result is already computed         if (memo[index, currSize, currOR] != -1) {             return memo[index, currSize, currOR];         }          // Include the current element and recurse         int include = MaxOrHelper(arr, n, k, index + 1,                                    currOR | arr[index],                                   currSize + 1, memo);          // Skip the current element and recurse         int exclude = MaxOrHelper(arr, n, k, index + 1,                                    currOR, currSize, memo);          // Store the result in the memoization table         memo[index, currSize, currOR] = Math.Max(include, exclude);          return memo[index, currSize, currOR];     }      static int MaxOrK(List<int> arr, int k) {         int n = arr.Count;                  // Create a memoization table with dimensions [n][k+1]         // [maximum possible OR value]         int maxPossibleOR = 0;                  foreach (int num in arr) {             maxPossibleOR |= num;         }          // Create a 3D memo table, initializing all values          // as -1         int[,,] memo = new int[n + 1, k + 1, maxPossibleOR + 1];                  // Initialize the memo table with -1         for (int i = 0; i <= n; i++) {             for (int j = 0; j <= k; j++) {                 for (int l = 0; l <= maxPossibleOR; l++) {                     memo[i, j, l] = -1;                 }             }         }          return MaxOrHelper(arr, n, k, 0, 0, 0, memo);     }      static void Main() {                List<int> arr = new List<int> { 2, 5, 3, 6, 11, 13 };         int k = 3;         Console.WriteLine(MaxOrK(arr, k));     } } 
JavaScript
// Javascript implementation to find Max OR of // subsequence of size k using Memoization  // Helper function with memoization function maxOrHelper(arr, n, k, index, currOR,                                 currSize, memo) {      // If we have selected k elements,      // return the current OR value     if (currSize === k) {         return currOR;     }      // If we have exhausted all elements     if (index === n) {         return 0;     }      // Check if the result is already computed     if (memo[index][currSize][currOR] !== -1) {         return memo[index][currSize][currOR];     }      // Include the current element and recurse     let include = maxOrHelper(arr, n, k, index + 1,                    currOR | arr[index], currSize + 1, memo);      // Skip the current element and recurse     let exclude = maxOrHelper(arr, n, k,                     index + 1, currOR, currSize, memo);      // Store the result in the memoization table     memo[index][currSize][currOR] = Math.max(include, exclude);      return memo[index][currSize][currOR]; }  function MaxOrK(arr, k) {     let n = arr.length;      // Create a memoization table with dimensions [n][k+1]     // [maximum possible OR value]     let maxPossibleOR = 0;      for (let num of arr) {         maxPossibleOR |= num;     }      // Create a 3D memo table, initializing all values     // as -1     let memo = Array.from({ length: n + 1 }, () =>         Array.from({ length: k + 1 }, () =>             Array(maxPossibleOR + 1).fill(-1)         )     );      return maxOrHelper(arr, n, k, 0, 0, 0, memo); }  let arr = [2, 5, 3, 6, 11, 13]; let k = 3; console.log(MaxOrK(arr, k)); 

Output
15 

Related article:

  •  Maximum Bitwise AND value of subsequence of length K


Next Article
Maximum Sum Subsequence of length k

S

stream_cipher
Improve
Article Tags :
  • Algorithms
  • Arrays
  • Bit Magic
  • Competitive Programming
  • DSA
  • Greedy
  • Sorting
  • Bitwise-OR
  • subsequence
Practice Tags :
  • Algorithms
  • Arrays
  • Bit Magic
  • Greedy
  • Sorting

Similar Reads

  • Maximum Bitwise AND value of subsequence of length K
    Given an array a of size N and an integer K. The task is to find the maximum bitwise and value of elements of any subsequence of length K. Note: a[i] <= 109 Examples: Input: a[] = {10, 20, 15, 4, 14}, K = 4 Output: 4 {20, 15, 4, 14} is the subsequence with highest '&' value. Input: a[] = {255
    15+ min read
  • Maximum Sum Subsequence of length k
    Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk. Examples: Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible s
    11 min read
  • Maximum sum subsequence of length K | Set 2
    Given an array sequence arr[] i.e [A1, A2 …An] and an integer k, the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3………<=Sk. Examples: Input: arr[] = {-1, 3, 4, 2, 5}, K = 3Output: 3 4 5Explanation: Subsequence 3 4 5 with sum 12 is the s
    7 min read
  • Maximum length subsequence possible of the form R^N K^N
    Given a string containing only two characters i.e. R and K (like RRKRRKKKKK). The task is to find the maximum value of N for a subsequence possible of the form R---N times and then K---N times (i.e. of the form R^N K^N). Note: String of k should be started after the string of R i.e. first k that wou
    6 min read
  • Maximum product of bitonic subsequence of size 3
    Given an array arr[] of positive integers of size N, the task is to find the maximum product of bitonic subsequence of size 3.Bitonic Subsequence: subsequence in which elements are first in the increasing order and then decreasing order. Elements in the subsequence are follow this order arr[i] <
    15 min read
  • Number of K length subsequences with minimum sum
    Given an array arr[] of size N and an integer K, the task is to find the number of K length subsequences of this array such that the sum of these subsequences is the minimum possible. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 1 Subsequences of length 2 are (1, 2), (1, 3), (1, 4), (2, 3),
    8 min read
  • Maximum product of subsequence of size k
    Given an array A[] of n integers, the task is to find a subsequence of size k whose product is maximum among all possible k sized subsequences of the given array. Constraints 1 <= n <= 10^5 1 <= k <= n Examples: Input : A[] = {1, 2, 0, 3}, k = 2 Output : 6 Explanation : Subsequence conta
    15 min read
  • Maximum sum of non-overlapping subarrays of length atmost K
    Given an integer array 'arr' of length N and an integer 'k', select some non-overlapping subarrays such that each sub-array if of length at most 'k', no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays are maximum.Examples: Input : arr[] = {-1, 2, -3, 4, 5}, k = 2 O
    10 min read
  • Length of longest subsequence whose XOR value is odd
    Given an array arr[] of N positive integers, the task is to find the length of the longest subsequence such that Bitwise XOR of all integers in the subsequence is odd. Examples: Input: N = 7, arr[] = {2, 3, 4, 1, 5, 6, 7}Output: 6Explanation: The subsequence of maximum length is {2, 3, 4, 5, 6, 7} w
    7 min read
  • Find subsequences with maximum Bitwise AND and Bitwise OR
    Given an array of n elements. The task is to print the maximum sum by selecting two subsequences of the array (not necessarily different) such that the sum of bitwise AND of all elements of the first subsequence and bitwise OR of all the elements of the second subsequence is maximum. Examples: Input
    4 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