Open In App

Find the Longest subarray such that difference between adjacent elements is K

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, and integer K. The task is to find the longest subarray with the difference between adjacent elements as K.

Examples:

Input: arr[] = { 5, 5, 5, 10, 8, 6, 12, 13 }, K =1
Output: {12, 13}
Explanation: This is the longest subarray with difference between adjacents as 1.

Input: arr[] = {4, 6, 8, 9, 8, 12, 14, 17, 15}, K = 2
Output: {4, 6, 8}

 

Approach: Starting from the first element of the array, find the first valid sub-array and store its length and starting point. Then starting from the next element (the first element that wasn’t included in the first sub-array), find another valid sub-array and keep on updating the maximum length and start point. Repeat the process until all the valid sub-arrays have been found then print the maximum length 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
// sub-array such that the
// absolute difference between every two
// consecutive elements is K
void getMaxLengthSubarray(int arr[],
                          int N, int K)
{
    int l = N;
    int i = 0, maxlen = 0;
    int max_len_start, max_len_end;
    while (i < l) {
        int j = i;
        while (i + 1 < l
               && (abs(arr[i]
                       - arr[i + 1]) == K)) {
            i++;
        }
 
        // Length of the valid sub-array
        // currently under consideration
        int currLen = i - j + 1;
 
        // Update the maximum length subarray
        if (maxlen < currLen) {
            maxlen = currLen;
            max_len_start = j;
            max_len_end = i;
        }
 
        if (j == i)
            i++;
    }
 
    // Print the maximum length subarray
    for (int p = max_len_start;
         p <= max_len_end; p++)
        cout << arr[p] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 4, 6, 8, 9, 8, 12,
                 14, 17, 15 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
    getMaxLengthSubarray(arr, N, K);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class GFG
{
 
// Function to return the maximum length
// sub-array such that the
// absolute difference between every two
// consecutive elements is K
static void getMaxLengthSubarray(int arr[],
                          int N, int K)
{
    int l = N;
    int i = 0, maxlen = 0;
    int max_len_start = 0, max_len_end = 0;
    while (i < l) {
        int j = i;
        while (i + 1 < l
               && (Math.abs(arr[i]
                       - arr[i + 1]) == K)) {
            i++;
        }
 
        // Length of the valid sub-array
        // currently under consideration
        int currLen = i - j + 1;
 
        // Update the maximum length subarray
        if (maxlen < currLen) {
            maxlen = currLen;
            max_len_start = j;
            max_len_end = i;
        }
 
        if (j == i)
            i++;
    }
 
    // Print the maximum length subarray
    for (int p = max_len_start;
         p <= max_len_end; p++)
        System.out.print(arr[p] + " ");
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 4, 6, 8, 9, 8, 12,
                 14, 17, 15 };
    int K = 2;
    int N =  arr.length; 
    getMaxLengthSubarray(arr, N, K);
}
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python program to implement
# the above approach
 
# Function to return the maximum length
# sub-array such that the
# absolute difference between every two
# consecutive elements is K
def getMaxLengthSubarray(arr, N, K) :
     
    l = N
    i = 0
    maxlen = 0
    while (i < l) :
        j = i
        while (i + 1 < l
               and (abs(arr[i]
                       - arr[i + 1]) == K)) :
            i += 1
         
        # Length of the valid sub-array
        # currently under consideration
        currLen = i - j + 1
 
        # Update the maximum length subarray
        if (maxlen < currLen) :
            maxlen = currLen
            max_len_start = j
            max_len_end = i
         
        if (j == i) :
            i += 1
     
    # Print the maximum length subarray
    for p in range(max_len_start, max_len_end+1, 1) :
        print(arr[p], end=" ")
 
# Driver code
arr = [ 4, 6, 8, 9, 8, 12,
                 14, 17, 15 ]
K = 2
N = len(arr)
getMaxLengthSubarray(arr, N, K)
 
# This code is contributed by avijitmondal1998


C#




// C# program for the above approach
using System;
class GFG
{
 
// Function to return the maximum length
// sub-array such that the
// absolute difference between every two
// consecutive elements is K
static void getMaxLengthSubarray(int []arr,
                          int N, int K)
{
    int l = N;
    int i = 0, maxlen = 0;
    int max_len_start = 0, max_len_end = 0;
    while (i < l) {
        int j = i;
        while (i + 1 < l
               && (Math.Abs(arr[i]
                       - arr[i + 1]) == K)) {
            i++;
        }
 
        // Length of the valid sub-array
        // currently under consideration
        int currLen = i - j + 1;
 
        // Update the maximum length subarray
        if (maxlen < currLen) {
            maxlen = currLen;
            max_len_start = j;
            max_len_end = i;
        }
 
        if (j == i)
            i++;
    }
 
    // Print the maximum length subarray
    for (int p = max_len_start;
         p <= max_len_end; p++)
        Console.Write(arr[p] + " ");
}
 
// Driver code
public static void Main()
{
    int []arr = { 4, 6, 8, 9, 8, 12,
                 14, 17, 15 };
    int K = 2;
    int N =  arr.Length; 
    getMaxLengthSubarray(arr, N, K);
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to return the maximum length
       // sub-array such that the
       // absolute difference between every two
       // consecutive elements is K
       function getMaxLengthSubarray(arr, N, K)
       {
           let l = N;
           let i = 0, maxlen = 0;
           let max_len_start, max_len_end;
           while (i < l) {
               let j = i;
               while (i + 1 < l
                   && (Math.abs(arr[i]
                       - arr[i + 1]) == K)) {
                   i++;
               }
 
               // Length of the valid sub-array
               // currently under consideration
               let currLen = i - j + 1;
 
               // Update the maximum length subarray
               if (maxlen < currLen) {
                   maxlen = currLen;
                   max_len_start = j;
                   max_len_end = i;
               }
 
               if (j == i)
                   i++;
           }
 
           // Print the maximum length subarray
           for (let p = max_len_start;
               p <= max_len_end; p++)
               document.write(arr[p] + " ");
       }
 
       // Driver code
       let arr = [4, 6, 8, 9, 8, 12,
           14, 17, 15];
       let K = 2;
       let N = arr.length;
       getMaxLengthSubarray(arr, N, K);
 
        // This code is contributed by Potta Lokesh
   </script>


 
 

Output

4 6 8 

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Similar Reads

Length of Longest subarray such that difference between adjacent elements is K
Given an array arr[] of size N, and integer K. The task is to find the length of the longest subarray with the difference between adjacent elements as K. Examples: Input: arr[] = { 5, 5, 5, 10, 8, 6, 12, 13 }, K =1Output: 2Explanation: Only one subarray which have difference between adjacents as 1 is {12, 13}. Input: arr[] = {4, 6, 8, 9, 8, 12, 14,
5 min read
Longest subarray such that adjacent elements have at least one common digit | Set 1
Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common. Examples: Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common in 43, 36. Input : 11 22 33 44 54 56 63 Output : 4
11 min read
Longest subarray such that adjacent elements have at least one common digit | Set - 2
Given an array of N integers, the task is to find the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common.Examples: Input : arr[] = {12, 23, 45, 43, 36, 97} Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common in 43, 36. Input : arr[] = {11, 22, 33, 44, 5
12 min read
Longest Subsequence such that difference between adjacent elements is either A or B
Given an array arr of size N, and two integers A and B. The task is to find the length of the longest subsequence with the difference between adjacent elements as either A or B. Example: Input : arr[]={ 5, 5, 5, 10, 8, 6, 12, 13 }, A=0, B=1Output : 4Explanation : Maximum length subsequence is {5,5,5,6} Input : arr[] = {4, 6, 7, 8, 9, 8, 12, 14, 17,
7 min read
Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one
Given an array arr[] consisting of N integers, the task is to find the length of the longest non-decreasing subsequence such that the difference between adjacent elements is at most 1. Examples: Input: arr[] = {8, 5, 4, 8, 4}Output: 3Explanation: {4, 4, 5}, {8, 8} are the two such non-decreasing subsequences of length 2 and 3 respectively. Therefor
6 min read
Longest subsequence such that difference between adjacent elements is K
Given an array arr[] of size N and an integer K, the task is to find the longest subsequence such that the difference between adjacents is K. Example: Input: arr[]={1, 2, 3, 4, 5, 3, 2}, K=1Output: 6Explanation: The longest subsequence with the difference between the adjacent elements as 1 is: {1, 2, 3, 4, 3, 2} Input: arr[]={1, 2, 3, 2, 3, 7, 2, 1
5 min read
Print longest Subsequence such that difference between adjacent elements is K
Given an array arr[] of size N, and integer K. The task is to find the longest subsequence with the difference between adjacent elements as K Examples: Input: arr[] = { 5, 5, 5, 10, 8, 6, 12, 13 }, K = 1Output: {5, 6} Input: arr[] = {4, 6, 7, 8, 9, 8, 12, 14, 17, 15}, K = 2Output: {4, 6, 8} Approach: The task can be solved with the help of dynamic
9 min read
Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd
Given an array arr[] of size N, having an equal number of even and odd integers, the task is to find the minimum number of subarrays required to be reversed to make the sum of pairs of adjacent elements odd. Examples: Input: arr[] = {13, 2, 6, 8, 3, 5, 7, 10, 14, 15} Output: 3Explanation:Step 1: Reverse subarray [2, 4] to modify the array to {13, 2
9 min read
Longest non-decreasing subsequence having difference between adjacent elements less than D
Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D. Examples: Input: arr[] = {1, 3, 2, 4, 5}, D = 2Output: 3Explanation:Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the
6 min read
Length of the longest increasing subsequence such that no two adjacent elements are coprime
Given an array arr[] of size N. The task is to find the length of the longest subsequence from the given array such that the sequence is strictly increasing and no two adjacent elements are coprime. Note: The elements in the given array are strictly increasing in order (1 &lt;= a[i] &lt;= 105) Examples: Input : a[] = { 1, 2, 3, 4, 5, 6} Output : 3
9 min read
Article Tags :
Practice Tags :