Last Updated: 19 Nov, 2020

Turbulent Hills

Easy
Asked in companies
VisaAirtelCoditas

Problem statement

You have been given an array/list HEIGHT denoting the heights of ‘N’ adjacent hills. The hills are said to be dangerous if their heights are turbulent.

A range of hills is turbulent if the comparison sign for their heights flips between each adjacent pair of hills. For example, if HEIGHT = [1, 2, 10, 3, 5, 1, 10, 10], then the hills in index range [1, 6] are turbulent as 2 < 10 > 3 < 5 > 1 < 10.

Your task is to find the length of the longest dangerous hill range.

Input Format:
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.

The first line of each test case contains a single integer ‘N’ representing the size of the array/list.

The second line of each test case contains ‘N’ single space-separated non-negative integers representing the array elements.
Output Format :
 For each test case, print the length of the longest dangerous hill range.

 Print the output of each test case in a separate line.
Note :
 You do not need to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 100
1 <= N <= 5000
0 <= HEIGHT[i] <= 10^5

Where ‘N’ is the number of elements in the array/list.

Time Limit: 1sec

Approaches

01 Approach

We have a simple brute force solution for this problem. We will traverse over all possible subarrays/ranges of the array and for each of them, check if it is turbulent. 

 

The key observation here is that a hill at index h ‘i’ constitutes to a dangerous range only if it either forms

  1. a peak (HEIGHT[i-2] < HEIGHT[i-1]  > HEIGHT[i]).
  2. or a valley (HEIGHT[i-2] > HEIGHT[i-1] < HEIGHT[i]).

02 Approach

We will maintain ‘currRange’ to track the length of the dangerous range ending at the current index. 

 

Traverse the array and update it as follows: 

  1. If the last three elements form a peak or a valley, we increment ‘currRange’ by 1.
  2. Otherwise, we no longer extend this range and reset ‘currRange’.
    1. We set ‘currRange’ to 1 if the previous and current element are the same.
    2. Else, we set ‘currRange’ to 2.

 

We will return the maximum value of ‘currRange’ encountered in the process as our final answer.