-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path1493.Longest Subarray of 1's After Deleting One Element.cpp
88 lines (80 loc) · 2.02 KB
/
1493.Longest Subarray of 1's After Deleting One Element.cpp
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
/*
written by Pankaj Kumar.
country:-INDIA
*/
typedef long long ll ;
const ll INF=1e18;
const ll mod1=1e9+7;
const ll mod2=998244353;
//Add main code here
// using vector
class Solution
{
public:
int longestSubarray(vector<int> &nums)
{
int n = nums.size();
vector<pair<int, int>> subarrays; // Vector to store subarray positions
int start = -1;
int end = -1;
// Find the positions of all subarrays of 1
for (int i = 0; i < n; i++)
{
if (nums[i] == 1)
{
if (start == -1)
start = i;
end = i;
}
else
{
if (start != -1)
{
subarrays.push_back({start, end});
start = -1;
end = -1;
}
}
}
// Edge case: If all elements are 1, return length - 1
if (start != -1)
subarrays.push_back({start, end});
int ans = 0;
int m = subarrays.size();
// Calculate the longest subarray length
for (int i = 0; i < m; i++)
{
ans = max(ans, subarrays[i].second - subarrays[i].first + 1);
if (i > 0 && subarrays[i].first == subarrays[i - 1].second + 2)
ans = max(ans, subarrays[i].second - subarrays[i - 1].first);
}
if(ans==n){
ans--;
}
return ans;
}
};
// sliding window approach
// class Solution
// {
// public:
// int longestSubarray(vector<int> &nums)
// {
// nums.insert(nums.begin(), 0);
// int sum = 0, ans = 0;
// for (unsigned i = 0, j = 0; j < nums.size(); j++)
// {
// if (nums[j] == 1)
// {
// sum += 1;
// }
// else
// {
// sum = j - i - 1;
// i = j;
// }
// ans = max(ans, sum);
// }
// return ans;
// }
// };