2419. Longest Subarray With Maximum Bitwise AND

T: O(n)
S: O(1)
class Solution {
    public int longestSubarray(int[] nums) {
        int maxNum = 0;
        int result = 0;

        int size = 0;
        for (int num : nums) {
            if (num > maxNum) {
                maxNum = num;
                size = 1;
                result = 1;
            } else if (num == maxNum) {
                size++;
            } else {
                size = 0;
            }
            result = Math.max(result, size);
        }
        return result;
    }
}
/**
T: O(n)
S: O(1)
find "longest subarray len" with maximum possible bitwise AND. 

means nums in a subarray -> AND together, and the result is the max one in all subarray
because it's AND
so the max AND will be the "max number" in this array

if 1 & 2 -> ans will become smaller than 2
means a big number AND a smaller number -> result will be smaller

so the max AND is only the max number in array, [1,2,3,3,2,2] -> ans is 3,3, len=2
3 AND 3 -> result is still 3, won't change
but it 3 AND other smaller number -> result becomes smaller

[1,2,3,4] -> ans is 4, len = 1

so we only need to find biggest number in this array and the continuous len of this number!
 */

Last updated