Increasing Subsegment

Posted: 6 Dec, 2020
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

Gary has a sequence 'ARR', consisting of 'N' integers.

We'll call a sequence ARR[i],  ARR[i+1], ..., ARR[j] where 1  ≤  i  ≤  j  ≤  N a subsegment of the sequence ARR. The value (j - i + 1) denotes the length of the subsegment.

Your task is to find the longest subsegment of ARR, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.

You need to return the length of the maximum subsegment that you can find by changing only one integer in the given sequence.

Input Format:
The first line contains a single integer T representing the number of test cases.      
Then T test cases follow.

The first line of test case contains an integer 'N' denoting the length of 'ARR'.

The second line of each test case contains 'N' space-separated integers denoting the elements of 'ARR'.
Output format:
For each test case, print the length of the maximum subsegment that you can find by changing only one integer in the given sequence.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 ≤ N ≤ 10^5
1 ≤  ARR[i]  ≤ 10^9

Time Limit: 1 sec
Approach 1

Here, the idea is to calculate the longest increasing subarray for every element by taking it as the starting as well as the ending point.

 

Here is the algorithm:

 

  1. We first compute the longest increasing subarray ending at an index for every index in the given array. We store these values in l[].
  2. Then calculate the longest increasing subarray starting at an index for every index in the given array. We store these values in r[].
  3. Update the answer ans = max ( ans, l[i-1] + r[i+1] + 1), when a[i-1] + 1 < a[i+1].
Try Problem