-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2401. Longest Nice Subarray
More file actions
59 lines (42 loc) · 1.79 KB
/
2401. Longest Nice Subarray
File metadata and controls
59 lines (42 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
2401. Longest Nice Subarray
DescriptionHintsSubmissionsDiscussSolutions
You are given an array nums consisting of positive integers.
We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.
Return the length of the longest nice subarray.
A subarray is a contiguous part of an array.
Note that subarrays of length 1 are always considered nice.
Example 1:
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
Example 2:
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
class Solution {
public int longestNiceSubarray(int[] nums) {
int usedBits = 0; // Tracks bits used in current window
int windowStart = 0; // Start position of current window
int maxLength = 0; // Length of longest nice subarray found
for (int windowEnd = 0; windowEnd < nums.length; ++windowEnd) {
// If current number shares bits with window, shrink window from left
// until there's no bit conflict
while ((usedBits & nums[windowEnd]) != 0) {
usedBits ^= nums[windowStart]; // Remove leftmost element's bits
windowStart++;
}
// Add current number to the window
usedBits |= nums[windowEnd];
// Update max length if current window is longer
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
return maxLength;
}
}