LeetCode Daily Question 978. The longest turbulence sub-array

978. The longest turbulence subarray

When the Asub-array A[i], A[i+1], ..., A[j]when the following conditions are met, we call it turbulent sub-array:

  • If i <= k < j, when kan odd number, A[k] > A[k+1]and when kan even A[k] < A[k+1]number, ;
  • Or, if i <= k < j, when kan even number, A[k] > A[k+1]and when kan odd A[k] < A[k+1]number, .

That is, if the comparison sign flips between each pair of adjacent elements in the sub-array, the sub-array is a turbulent sub-array.

Returns the Amaximum length of the subarray of turbulence.

Example 1:

输入:[9,4,2,10,7,8,8,1,9]
输出:5
解释:(A[1] > A[2] < A[3] > A[4] < A[5])

Example 2:

输入:[4,8,12,16]
输出:2

Example 3:

输入:[100]
输出:1

prompt:

  • 1 <= A.length <= 40000
  • 0 <= A[i] <= 10^9

Method One: Strong Lu

Problem-solving ideas

  • No special skills, traverse the array once, compare the numbers one by one, and find out the length of the sub-array

Reference Code

public int maxTurbulenceSize(int[] arr) {
    
    
    int n = arr.length, idx = 0;
    int ret = 1, preState = 0;
    for (int i = 1; i < n; i++) {
    
    
        int state = Integer.compare(arr[i], arr[i - 1]);
        if (state == preState || state == 0) {
    
    
            ret = Math.max(ret, i - idx);
            idx = state == 0 ? i : i - 1;
        }
        preState = state;
    }
    return Math.max(ret, n - idx);
}

Results of the
Insert picture description here

Method two: dynamic programming

Problem-solving ideas

  • State definition: each corner is marked with three states, namely uphill, downhill, and flat (equal to the previous number)
    1. up[i]It denotes the index of ia sub-array length during uphill
    2. down[i]Denotes the index of ia sub-array when the length downhill
    3. If it is flat, then down[i] = up[i] = 1
  • Initialization: Let the two arrays be all 1.
  • State transition:
    1. Index iis uphill:up[i] = down[i] + 1
    2. Index idownhill:down[i] = up[i] + 1
    3. Index iis flat, do not do anything (can not initialize, so here down[i] = up[i] = 1)

Reference Code

public int maxTurbulenceSize(int[] arr) {
    
    
    int n = arr.length;
    int[] up = new int[n], down = new int[n];
    Arrays.fill(up, 1);
    Arrays.fill(down, 1);
    int ret = 1;
    for (int i = 1; i < n; i++) {
    
    
        if (arr[i] > arr[i - 1]) {
    
    
            up[i] = down[i - 1] + 1;
        } else if(arr[i] < arr[i - 1]) {
    
    
            down[i] = up[i - 1] + 1;
        }
        ret = Math.max(ret, Math.max(up[i], down[i]));
    }
    return ret;
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113761907