aboutsummaryrefslogtreecommitdiff
path: root/long_nice_subarr.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-17 18:32:43 -0600
committerJack Sangdahl <[email protected]>2025-03-17 18:32:43 -0600
commita1f80208dda2f142674ed9dc260063009e96dee1 (patch)
treef5c1d2e6416132c35dac010b4640b40edbe8e57f /long_nice_subarr.py
parent5b627305f75df05f28670508f2e7b30f094000d0 (diff)
downloadleetcode-a1f80208dda2f142674ed9dc260063009e96dee1.tar.gz
leetcode-a1f80208dda2f142674ed9dc260063009e96dee1.zip
2401. longest nice subarray
Diffstat (limited to 'long_nice_subarr.py')
-rw-r--r--long_nice_subarr.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/long_nice_subarr.py b/long_nice_subarr.py
new file mode 100644
index 0000000..037743e
--- /dev/null
+++ b/long_nice_subarr.py
@@ -0,0 +1,31 @@
+# 2401. Longest Nice Subarray
+
+"""
+given an array 'nums' consisting of positive integers. we call a subarray of
+'nums' nice if the bitwise cnt 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 contiguous part of an array. note that
+subarrays of length 1 are always considered nice.
+"""
+
+
+class Solution(object):
+ def longestNiceSubarray(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ cnt, i, ans = 0, 0, 0
+ for j in range(len(nums)):
+ while cnt & nums[j]:
+ cnt ^= nums[i]
+ i += 1
+ cnt |= nums[j]
+ ans = max(ans, j - i + 1)
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.longestNiceSubarray(nums=[1, 3, 8, 48, 10]))
+ print(obj.longestNiceSubarray(nums=[3, 1, 5, 11, 13]))