LeetCode in Kotlin

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:

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:

Solution

class Solution {
    fun longestNiceSubarray(nums: IntArray): Int {
        var ans = 1
        var left = 0
        var right = 0
        while (right < nums.size) {
            for (i in right - 1 downTo left) {
                if (nums[i] and nums[right] != 0) {
                    left = i + 1
                    break
                }
                if (i == left) {
                    ans = ans.coerceAtLeast(right - left + 1)
                }
            }
            right++
        }
        return ans
    }
}