[LeetCode] 2419. Longest Subarray With Maximum Bitwise AND

CNoodle發表於2024-09-15

You are given an integer array nums of size n.

Consider a non-empty subarray from nums that has the maximum possible bitwise AND.

In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.

The bitwise AND of an array is the bitwise AND of all the numbers in it.

A subarray is a contiguous sequence of elements within an array.

Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.

Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106

按位與最大的最長子陣列。

給你一個長度為 n 的整數陣列 nums 。

考慮 nums 中進行 按位與(bitwise AND)運算得到的值 最大 的 非空 子陣列。

換句話說,令 k 是 nums 任意 子陣列執行按位與運算所能得到的最大值。那麼,只需要考慮那些執行一次按位與運算後等於 k 的子陣列。
返回滿足要求的 最長 子陣列的長度。

陣列的按位與就是對陣列中的所有數字進行按位與運算。

子陣列 是陣列中的一個連續元素序列。

思路

這道題考察的是對位運算的敏感度吧我覺得。注意 AND 運算有一個特點,假如你有一個足夠大的數字,比如 15 好了,他的二進位制表達是 1111(四個 1)。如果 15 是陣列裡最大的數字,那麼他跟任何其他數字做 AND 操作的結果都只會讓結果變得更小,因為其他比 15 小的數字的二進位制表達裡面包含 0,與 15 AND 之後,結果只會比 15 更小。

所以這道題我們找到陣列最大值 max 之後,需要判斷連續的 max 到底有幾個。最後返回最長的子陣列的長度。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

class Solution {
    public int longestSubarray(int[] nums) {
        int max = 0, res = 0, cnt = 0;
        // First pass: find the maximum element
        for (int num : nums) {
            max = Math.max(max, num);
        }

        // Second pass: count the longest subarray of max elements
        for (int num : nums) {
            if (num == max) {
                cnt++;
                res = Math.max(res, cnt);
            } else {
                cnt = 0; // reset count when encountering a different element
            }
        }
        return res;
    }
}

相關文章