Leetcode: Longest Turbulent Subarray


This question is asked at Amazon and Morgan Stanley. It is as follows and utilizes Arrays, Dynamic Programming, and the Sliding Window. Here it is:

Given an integer array arr, return the length of a maximum size turbulent subarray of r. A subarray is turbulent if comparison sign flips between each adjacent pair of elements in the subarray. 

For example, if 

i<=k<j, then arr[k] > arr[k+1] if k is odd and arr[k]<arr[k+1] when k is even for a subarray [arr[i], ..., arr[j]]. It can also be the other way around as well, so each comparison is flipped. For example the 0th element is greater than the first element, first element greater than the second element, etc.

Here's an example:


Input: arr = [9,4,2,10,7,8,8,1,9]

Output: 5

Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]


So it goes up and down like valleys and mountains.

So, let's get to the code:  

We will do a 2 pointer approach to see if something is a valley or a mountain.

The start index will be 0 and the end will start from start + 1 or start. We will check if the current n index is forming a valley or a mountain. The length is equal to end - start + 1. We keep moving in the iteration until we find an unhealthy case. We abort the condition when it is neither a mountain or a valley condition. 

 We will skip the start when the start and the start + 1 values are the same. 


Here is the method: 


class Solution {

    public int maxTurbulenceSize(int[] arr) {

        if(arr.length < 2) return arr.length; //base case

        int max = 1;

        int start = 0;

        int end = 0; 

        int len = arr.length; 

        //2 pointer method.

        while(start + 1 < len) {

            //base case

            if(arr[start] == arr[start + 1]) {

                 start++;

                 continue;

            }

            end = start + 1;

            //see turbulence until there is no more. 

            while(end + 1 < len && isCurrentIndexTurbulent(arr, end)) {

                end++;

            }

            max = Math.max(max, end - start + 1);

            start = end;

        }

        return max; 

    }

    private boolean isCurrentIndexTurbulent(int[] arr, int k) {

        //peak or valley

        return (arr[k] > arr[k - 1] && arr[k] > arr[k + 1]) || (arr[k] < arr[k - 1]) && (arr[k] < arr[k + 1]);

    }

}

Comments

Popular Posts