From 431feddf516188d11807de78005eadb2f243bd23 Mon Sep 17 00:00:00 2001 From: Rohit-Sarkar55 <71070509+Rohit-Sarkar55@users.noreply.github.com> Date: Mon, 10 Oct 2022 19:39:06 +0530 Subject: [PATCH] 2401. Longest Nice Subarray Accepted Solution Problem Link: https://leetcode.com/contest/weekly-contest-309/problems/longest-nice-subarray/ Please merge this pull request under hacktoberfest tag --- Longest_Nice_Subarray.cpp | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Longest_Nice_Subarray.cpp diff --git a/Longest_Nice_Subarray.cpp b/Longest_Nice_Subarray.cpp new file mode 100644 index 0000000..439b1b5 --- /dev/null +++ b/Longest_Nice_Subarray.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int longestNiceSubarray(vector& nums) { + vector bit(32 , 0); + int ans = 0; + int n = nums.size(); + int f1 = 1 ,f2 = 1, i =0 , j= 0; + while(f1 || f2){ + f1 = 0; + f2 = 0; + + + while(i < n && check(bit) ) { + f1 = 1; + int num = nums[i]; + for(int d=31; d>=0; d--){ + if(((num>>d)&1)) bit[d]++; + } + + if(check(bit)){ + ans = max(ans , i- j + 1); + } + i++; + } + + while( j < i && !(check(bit))) { + f2 = 1; + int num = nums[j]; + for(int d=31; d>=0; d--){ + if(((num>>d)&1)) bit[d]--; + } + j++; + } + + } + return ans; + } + + bool check(vector &v){ + for(int i: v){ + if(i >= 2) return 0; + } + return 1; + } +};