Skip to content

Commit 92c8692

Browse files
authored
Merge pull request #256 from gg21-prog/feat/adjacent-increasing-subarrays
3350. Adjacent Increasing Subarrays Detection II.cpp
2 parents 88773f7 + 58c4299 commit 92c8692

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
using namespace std;
3+
/*
4+
APPROACH:
5+
Use an array to track lengths of increasing streaks, then apply binary search
6+
to find the largest k for which two adjacent increasing subarrays exist.
7+
*/
8+
bool check(int *inc, int n, int k)
9+
{
10+
for (int end1 = k - 1; end1 + k < n; end1++)
11+
{
12+
if (inc[end1] >= k && inc[end1 + k] >= k)
13+
{
14+
return true;
15+
}
16+
}
17+
return false;
18+
}
19+
20+
int maxIncreasingSubarrays(int *nums, int numsSize)
21+
{
22+
int n = numsSize;
23+
int inc[n];
24+
for (int i = 0; i < n; i++)
25+
inc[i] = 1;
26+
27+
// Build the increasing streak lengths
28+
for (int i = 1; i < n; i++)
29+
{
30+
if (nums[i] > nums[i - 1])
31+
{
32+
inc[i] = inc[i - 1] + 1;
33+
}
34+
}
35+
36+
int L = 1, R = n / 2;
37+
int ans = 0;
38+
39+
// Binary search for max k
40+
while (L <= R)
41+
{
42+
int mid = L + (R - L) / 2;
43+
if (check(inc, n, mid))
44+
{
45+
ans = mid; // mid works, try bigger k
46+
L = mid + 1;
47+
}
48+
else
49+
{
50+
R = mid - 1; // mid too big, try smaller k
51+
}
52+
}
53+
54+
return ans;
55+
}

0 commit comments

Comments
 (0)