g2401_2500.s2401_longest_nice_subarray.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2401_2500.s2401_longest_nice_subarray;
// #Medium #Array #Bit_Manipulation #Sliding_Window
// #2022_09_26_Time_4_ms_(87.45%)_Space_70.5_MB_(79.87%)
/**
* 2401 - Longest Nice Subarray\.
*
* Medium
*
* 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
**/
public class Solution {
public int longestNiceSubarray(int[] nums) {
int ans = 1;
int left = 0;
int right = 0;
while (right < nums.length) {
for (int i = right - 1; i >= left; i--) {
if ((nums[i] & nums[right]) != 0) {
left = i + 1;
break;
}
if (i == left) {
ans = Math.max(ans, right - left + 1);
}
}
right++;
}
return ans;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy