![]() |
VOOZH | about |
Given a positive integer array arr[] of size N, the task is to print the longest non-empty subarray whose bitwise AND is maximum in the array.
Examples:
Input: arr[ ] = {1, 5, 5, 2, 2, 2, 4, 5, 7, 7, 7, 7}
Output: 7, 7, 7, 7
Explanation: The maximum Bitwise AND is 7 and the longest subarray whose bitwise AND is 7 is from index 8 to index 11.Input: arr[ ]={3, 2, 6, 9, 4}
Output: 9
Naive Approach
The idea is to find all subarray and in those subarrays pick those subarrays which has maximum Bitwise AND. After that return/print that subarray which has the longest length
Steps to implement-
Code-
Output-
7 7 7 7
Time Complexity: O(N3), because of two nested loops to find all subarray and a third loop to insert required subarray into vector
Auxiliary Space: O(N), for storing answer
Approach: The approach for code will be:
It is always better to take the maximum element and find the longest continous subarray having only the maximum element of the array.
Steps involved in the implementation of the code:
Below is the implementation for the above approach:
7 7 7 7
Time Complexity: O(n)
Auxiliary Space: O(1)