-
Notifications
You must be signed in to change notification settings - Fork 2
/
Length of the longest subarray with positive product
94 lines (58 loc) · 1.45 KB
/
Length of the longest subarray with positive product
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution {
public:
// Function to return the length of the
//longest subarray with ppositive product
int maxLength(vector<int> &arr,int n){
int maxlen=0,cnt_neg=0,strt=0,end=0;
int neg_pos=-1;
for(end;end<n;end++){
if(arr[end]==0){
strt=end+1;
cnt_neg=0;
neg_pos=-1;
}
else if(arr[end]>0){
if(cnt_neg&1 ){
maxlen=max(maxlen,end-neg_pos);
}
else
{
maxlen=max(maxlen,end-strt+1);
}
}
else{
cnt_neg++;
if(cnt_neg==1)
neg_pos=end;
if(cnt_neg%2==0){
maxlen=max(maxlen,end-strt+1);
}
}
}
return maxlen;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> arr(n);
for(int i = 0;i<n;i++){
cin>>arr[i];
}
Solution ob;
int res = ob.maxLength(arr,n);
cout<<res<<"\n";
}
return 0;
}
// } Driver Code Ends