Maximum length subarray with difference between adjacent elements as either 0 or 1

Given an array of n integers. The task is to find the maximum length of the sub-array such that absolute difference between all the consecutive elements of the sub-array is either 0 or 1.
Examples:Â
Â
Input: arr[] = {2, 5, 6, 3, 7, 6, 5, 8}Â
Output: 3Â
{5, 6} and {7, 6, 5} are the only valid sub-arrays.
Input: arr[] = {-2, -1, 5, -1, 4, 0, 3}Â
Output: 2Â
Â
Â
Approach: Starting from the first element of the array, find the first valid sub-array and store it’s length then starting from the next element (the first element that wasn’t included in the first sub-array), find another valid sub-array. Repeat the process until all the valid sub-arrays have been found then print the length of the maximum sub-array.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std;Â
// Function to return the maximum length// of the sub-array such that the// absolute difference between every two// consecutive elements is either 1 or 0int getMaxLength(int arr[],int n){Â Â Â Â int l = n;Â Â Â Â int i = 0, maxlen = 0;Â Â Â Â while (i < l)Â Â Â Â {Â Â Â Â Â Â Â Â int j = i;Â Â Â Â Â Â Â Â while (i+1 < l &&Â Â Â Â Â Â Â Â Â Â Â Â Â (abs(arr[i] - arr[i + 1]) == 1 ||Â Â Â Â Â Â Â Â Â Â Â Â Â abs(arr[i] - arr[i + 1]) == 0)) Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â i++;Â Â Â Â Â Â Â Â }Â
            // Length of the valid sub-array currently            // under consideration            int currLen = i - j + 1;Â
            // Update the maximum length            if (maxlen < currLen)                maxlen = currLen;Â
            if (j == i)                i++;    }Â
    // Any valid sub-array cannot be of length 1    //maxlen = (maxlen == 1) ? 0 : maxlen;Â
    // Return the maximum possible length    return maxlen;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 2, 4 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << getMaxLength(arr, n);}Â
// This code is contributed by// Surendra_Gangwar |
Java
// Java implementation of the approachpublic class GFG {Â
    // Function to return the maximum length    // of the sub-array such that the    // absolute difference between every two    // consecutive elements is either 1 or 0    public static int getMaxLength(int arr[])    {Â
        int l = arr.length;        int i = 0, maxlen = 0;        while (i < l) {            int j = i;            while (i + 1 < l                   && (Math.abs(arr[i] - arr[i + 1]) == 1                       || Math.abs(arr[i] - arr[i + 1]) == 0)) {                i++;            }Â
            // Length of the valid sub-array currently            // under cosideration            int currLen = i - j + 1;Â
            // Update the maximum length            if (maxlen < currLen)                maxlen = currLen;Â
            if (j == i)                i++;        }Â
        // Any valid sub-array cannot be of length 1        maxlen = (maxlen == 1) ? 0 : maxlen;Â
        // Return the maximum possible length        return maxlen;    }Â
    // Driver code    public static void main(String[] args)    {        int arr[] = { 2, 4 };        System.out.print(getMaxLength(arr));    }} |
Python3
# Python3 implementation of the approach Â
# Function to return the maximum length # of the sub-array such that the # absolute difference between every two # consecutive elements is either 1 or 0 def getMaxLength(arr, n) :         l = n;     i = 0; maxlen = 0;         while (i < l) :        j = i;         while (i + 1 < l and              (abs(arr[i] - arr[i + 1]) == 1 or               abs(arr[i] - arr[i + 1]) == 0)) :                     i += 1;                  # Length of the valid sub-array         # currently under cosideration         currLen = i - j + 1; Â
        # Update the maximum length         if (maxlen < currLen) :             maxlen = currLen; Â
        if (j == i) :            i += 1;          # Any valid sub-array cannot be of length 1     # maxlen = (maxlen == 1) ? 0 : maxlen; Â
    # Return the maximum possible length     return maxlen;      # Driver code if __name__ == "__main__" :Â
    arr = [ 2, 4 ];     n = len(arr)     print(getMaxLength(arr, n)); Â
# This code is contributed by Ryuga |
C#
// C# implementation of the approach using System;Â
class GFG { Â
    // Function to return the maximum length     // of the sub-array such that the     // Absolute difference between every two     // consecutive elements is either 1 or 0     public static int getMaxLength(int []arr)     { Â
        int l = arr.Length;         int i = 0, maxlen = 0;         while (i < l)         {             int j = i;             while (i + 1 < l &&                     (Math.Abs(arr[i] - arr[i + 1]) == 1 ||                    Math.Abs(arr[i] - arr[i + 1]) == 0))             {                 i++;             } Â
            // Length of the valid sub-array currently             // under consideration             int currLen = i - j + 1; Â
            // Update the maximum length             if (maxlen < currLen)                 maxlen = currLen; Â
            if (j == i)                 i++;         } Â
        // Any valid sub-array cannot be of length 1         maxlen = (maxlen == 1) ? 0 : maxlen; Â
        // Return the maximum possible length         return maxlen;     } Â
    // Driver code     public static void Main(String []args)     {         int []arr = { 2, 4 };         Console.Write(getMaxLength(arr));     } } Â
// This code is contributed by Arnab Kundu |
PHP
<?php// PHP implementation of the approachÂ
// Function to return the maximum length// of the sub-array such that the// absolute difference between every two// consecutive elements is either 1 or 0function getMaxLength($arr, $n){Â Â Â Â $l = $n;Â Â Â Â $i = 0;Â Â Â Â $maxlen = 0;Â Â Â Â while ($i < $l)Â Â Â Â {Â Â Â Â Â Â Â Â $j = $i;Â Â Â Â Â Â Â Â while ($i + 1 < $l &&Â Â Â Â Â Â Â Â Â Â Â Â Â Â (abs($arr[$i] - $arr[$i + 1]) == 1 ||Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â abs($arr[$i] - $arr[$i + 1]) == 0)) Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â $i++;Â Â Â Â Â Â Â Â }Â
        // Length of the valid sub-array         // currently under consideration        $currLen = $i - $j + 1;Â
        // Update the maximum length        if ($maxlen < $currLen)            $maxlen = $currLen;Â
        if ($j == $i)            $i++;    }Â
    // Any valid sub-array cannot be of length 1    //maxlen = (maxlen == 1) ? 0 : maxlen;Â
    // Return the maximum possible length    return $maxlen;}Â
// Driver code$arr = array(2, 4 );$n = sizeof($arr);echo getMaxLength($arr, $n)Â
// This code is contributed by ita_c?> |
Javascript
<script>Â
// Javascript implementation of the approachÂ
// Function to return the maximum length    // of the sub-array such that the    // absolute difference between every two    // consecutive elements is either 1 or 0function getMaxLength(arr){    let l = arr.length;        let i = 0, maxlen = 0;        while (i < l) {            let j = i;            while (i + 1 < l                   && (Math.abs(arr[i] - arr[i + 1]) == 1                       || Math.abs(arr[i] - arr[i + 1]) == 0)) {                i++;            }               // Length of the valid sub-array currently            // under cosideration            let currLen = i - j + 1;               // Update the maximum length            if (maxlen < currLen)                maxlen = currLen;               if (j == i)                i++;        }           // Any valid sub-array cannot be of length 1        //maxlen = (maxlen == 1) ? 0 : maxlen;           // Return the maximum possible length        return maxlen;}Â
// Driver codelet arr = [2, 4 ];document.write(getMaxLength(arr));Â
// This code is contributed by rag2127.</script> |
1
Â
Time Complexity : O(n) ,where n is size of given array.
Space Complexity : O(1) ,as we are not using any extra space.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



