Open In App

Longest alternating Subarray with absolute difference at least K

Last Updated : 19 Oct, 2023
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 that has alternating even and odd integers such that the absolute difference between the first and last element of the subarray is greater than or equal to K.

Examples:                                                                                                                                                                                                                                      

Input:  N = 6, K = 3, array = {2, 5, 4, 7, 8, 9}
Output: 6
Explanation: The longest subarray that satisfies the condition is [2, 5, 4, 7, 8, 9]. It has length 6 and starts with an even integer and ends with an odd integer. The absolute difference between the first and last element is |2 – 9| = 7 which is greater than or equal to K.

Input: N = 8, K = 5, array = {1, -6, 3, 10, -5, -2, -7, 12}
Output: 4
Explanation: The longest subarray that satisfies the condition is [10, -5, -2, -7]. It has length 4 and starts with an even integer and ends with an odd integer. The absolute difference between the first and last element is |10 – (-7)| =17 which is greater than or equal to K.

Approach: The way to solve the problem is as follows:

For each index, find the longest alternating subarray that starts with an even integer or an odd integer, and update the result if the length is greater than the current value.

Steps involved in the implementation of the code:

  • Initialize a variable max_length to 0.
  • Iterate through all possible subarrays of the given array using two nested loops.
  • For each subarray, check if the first and last elements have an absolute difference greater than or equal to K and if the subarray starts with an even integer and ends with an odd integer (or vice versa).
  • If the subarray meets the conditions, calculate its length and update max_length if the length is greater than max_length.
  • After all, subarrays have been checked, return max_length.

Below is the implementation for the above approach:

C++




// C++ implementation of the code
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length of longest
// alternating subarray
int longest_alternating_subarray(int arr[], int n, int k)
{
    int max_length = 0;
 
    // Loop over all possible subarrays
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // Check if absolute difference
            // between first and last
            // elements is >= k
            if (abs(arr[i] - arr[j]) < k) {
 
                // If not, skip this subarray
                continue;
            }
 
            // Check if subarray starts
            // with even and ends with
            // odd (or vice versa)
            if ((arr[i] % 2 == 0 && arr[j] % 2 != 0)
                || (arr[i] % 2 != 0 && arr[j] % 2 == 0)) {
                int length = j - i + 1;
                if (length > max_length) {
 
                    // Update maximum length
                    // if current length
                    // is greater
                    max_length = length;
                }
            }
        }
    }
 
    // Return maximum length of
    // alternating subarray
    return max_length;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 5, 4, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    // Function call
    int length = longest_alternating_subarray(arr, n, k);
    cout << length << endl;
 
    return 0;
}


Java




// Java implementation of the code
import java.io.*;
 
class GFG {
    // Function to find the length of longest
    // alternating subarray
    public static int
    longest_alternating_subarray(int arr[], int n, int k)
    {
        int max_length = 0;
 
        // Loop over all possible subarrays
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Check if absolute difference
                // between first and last
                // elements is >= k
                if (Math.abs(arr[i] - arr[j]) < k) {
 
                    // If not, skip this subarray
                    continue;
                }
 
                // Check if subarray starts
                // with even and ends with
                // odd (or vice versa)
                if ((arr[i] % 2 == 0 && arr[j] % 2 != 0)
                    || (arr[i] % 2 != 0
                        && arr[j] % 2 == 0)) {
                    int length = j - i + 1;
                    if (length > max_length) {
 
                        // Update maximum length
                        // if current length
                        // is greater
                        max_length = length;
                    }
                }
            }
        }
 
        // Return maximum length of
        // alternating subarray
        return max_length;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 2, 5, 4, 7, 8, 9 };
        int n = arr.length;
        int k = 3;
 
        // Function call
        int length
            = longest_alternating_subarray(arr, n, k);
        System.out.println(length);
    }
}
 
// This code is contributed by Rohit Pradhan


Python3




import math
 
def longest_alternating_subarray(arr, n, k):
    max_length = 0
 
    # Loop over all possible subarrays
    for i in range(n):
        for j in range(i + 1, n):
 
            # Check if absolute difference between first
            # and last elements is >= k
            if abs(arr[i] - arr[j]) < k:
                # If not, skip this subarray
                continue
 
            # Check if subarray starts with even and ends with odd (or vice versa)
            if ((arr[i] % 2 == 0 and arr[j] % 2 != 0) or
                    (arr[i] % 2 != 0 and arr[j] % 2 == 0)):
                length = j - i + 1
                if length > max_length:
                    # Update maximum length if current length is greater
                    max_length = length
 
    # Return maximum length of alternating subarray
    return max_length
 
# Driver code
arr = [2, 5, 4, 7, 8, 9]
n = len(arr)
k = 3
length = longest_alternating_subarray(arr, n, k)
print(length)
# This Code is Contributed By Vikas Bishnoi


C#




// C# implementation of the code
using System;
 
class GFG {
    // Function to find the length of longest
    // alternating subarray
    public static int
    longest_alternating_subarray(int[] arr, int n, int k)
    {
        int max_length = 0;
 
        // Loop over all possible subarrays
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // Check if absolute difference
                // between first and last
                // elements is >= k
                if (Math.Abs(arr[i] - arr[j]) < k) {
 
                    // If not, skip this subarray
                    continue;
                }
 
                // Check if subarray starts
                // with even and ends with
                // odd (or vice versa)
                if ((arr[i] % 2 == 0 && arr[j] % 2 != 0)
                    || (arr[i] % 2 != 0
                        && arr[j] % 2 == 0)) {
                    int length = j - i + 1;
                    if (length > max_length) {
 
                        // Update maximum length
                        // if current length
                        // is greater
                        max_length = length;
                    }
                }
            }
        }
 
        // Return maximum length of
        // alternating subarray
        return max_length;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 2, 5, 4, 7, 8, 9 };
        int n = arr.Length;
        int k = 3;
 
        // Function call
        int length
            = longest_alternating_subarray(arr, n, k);
        Console.WriteLine(length);
    }
}
 
// This code is contributed by Vaibhav nandan


Javascript




function longestAlternatingSubarray(arr, n, k) {
  let maxLength = 0;
 
  // Loop over all possible subarrays
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      // Check if absolute difference
      // between first and last
      // elements is >= k
      if (Math.abs(arr[i] - arr[j]) < k) {
        // If not, skip this subarray
        continue;
      }
 
      // Check if subarray starts
      // with even and ends with
      // odd (or vice versa)
      if (
        (arr[i] % 2 === 0 && arr[j] % 2 !== 0) ||
        (arr[i] % 2 !== 0 && arr[j] % 2 === 0)
      ) {
        const length = j - i + 1;
        if (length > maxLength) {
          // Update maximum length
          // if current length
          // is greater
          maxLength = length;
        }
      }
    }
  }
 
  // Return maximum length of
  // alternating subarray
  return maxLength;
}
 
// Driver code
const arr = [2, 5, 4, 7, 8, 9];
const n = arr.length;
const k = 3;
 
// Function call
const length = longestAlternatingSubarray(arr, n, k);
console.log(length);
 
 
//Thsi code is contributed by Tushar Rokade


Output

6








Time complexity: O(N^2)
Auxiliary space: O(1)

Alternative Approach: Using Two-Pointer approach.

The algorithm finds the longest subarray with alternating even and odd numbers, ensuring the absolute difference between the first and last elements is at least K.

It uses a two-pointer approach to scan the array, maintaining the current length of the alternating subarray. When the alternating condition is broken, it updates the left pointer and resets the current length. The maximum length satisfying the given conditions is returned.

C++14




#include <iostream>
#include <vector>
#include <cmath>
// function to find longest alternating subarray
int longest_alternating_subarray(std::vector<int>& arr, int K) {
    int n = arr.size();
    int left = 0;
    int max_length = 0;
    int current_length = 1;
    int last_element = arr[0];
   
      // Traversing through array
    for (int right = 1; right < n; right++) {
       
          // Increase current_length if one or both of last_element and right most element of subarray is odd
        if ((arr[right] % 2 == 0 && last_element % 2 != 0) || (arr[right] % 2 != 0 && last_element % 2 == 0)) {
            current_length += 1;
        } else {
            left = right - 1;
            current_length = 1;
        }
       
          // checking difference between first and last element is at least k
        if (std::abs(arr[left] - arr[right]) >= K) {
            max_length = std::max(max_length, current_length);
        }
        last_element = arr[right];
    }
    return max_length;
}
 
// Driver code
int main() {
    int N = 6;
    int K = 3;
    std::vector<int> array = {2, 5, 4, 7, 8, 9};
    std::cout << longest_alternating_subarray(array, K) << std::endl;
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function to find the longest alternating subarray
    static int longestAlternatingSubarray(List<Integer> arr, int K) {
        int n = arr.size();
        int left = 0;
        int maxLength = 0;
        int currentLength = 1;
        int lastElement = arr.get(0);
 
        // Traversing through the array
        for (int right = 1; right < n; right++) {
            // Increase currentLength if one or both of lastElement and the rightmost element of the subarray is odd
            if ((arr.get(right) % 2 == 0 && lastElement % 2 != 0) || (arr.get(right) % 2 != 0 && lastElement % 2 == 0)) {
                currentLength += 1;
            } else {
                left = right - 1;
                currentLength = 1;
            }
 
            // Check if the absolute difference between the first and last element is at least K
            if (Math.abs(arr.get(left) - arr.get(right)) >= K) {
                maxLength = Math.max(maxLength, currentLength);
            }
            lastElement = arr.get(right);
        }
        return maxLength;
    }
 
    // Driver code
    public static void main(String[] args) {
        int N = 6;
        int K = 3;
        List<Integer> array = new ArrayList<>();
        array.add(2);
        array.add(5);
        array.add(4);
        array.add(7);
        array.add(8);
        array.add(9);
 
        System.out.println(longestAlternatingSubarray(array, K));
    }
}


Python3




#Python code implementation of the above approach:
def longest_alternating_subarray(arr, K):
    n = len(arr)
    left = 0
    max_length = 0
    current_length = 1
    last_element = arr[0]
 
    for right in range(1, n):
        if (arr[right] % 2 == 0 and last_element % 2 != 0) or (arr[right] % 2 != 0 and last_element % 2 == 0):
            current_length += 1
        else:
            left = right - 1
            current_length = 1
 
        if abs(arr[left] - arr[right]) >= K:
            max_length = max(max_length, current_length)
 
        last_element = arr[right]
 
    return max_length
 
# Example usage
N = 6
K = 3
array = [2, 5, 4, 7, 8, 9]
print(longest_alternating_subarray(array, K))  # Output: 6


C#




using System;
 
public class Program
{
    public static int LongestAlternatingSubarray(int[] arr, int K)
    {
        int n = arr.Length;
        int left = 0;
        int maxLength = 0;
        int currentLength = 1;
        int lastElement = arr[0];
       
          // Traversing through array
        for (int right = 1; right < n; right++)
        {
              // Increase current_length if one or both of last_element
            // and right most element of subarray is odd
            if ((arr[right] % 2 == 0 && lastElement % 2 != 0) ||
                (arr[right] % 2 != 0 && lastElement % 2 == 0))
            {
                currentLength += 1;
            }
            else
            {
                left = right - 1;
                currentLength = 1;
            }
           
              // checking difference between first and last element is at least k
            if (Math.Abs(arr[left] - arr[right]) >= K)
            {
                maxLength = Math.Max(maxLength, currentLength);
            }
            lastElement = arr[right];
        }
        return maxLength;
    }
 
      // Driver code
    public static void Main(string[] args)
    {
        //int N = 6;
        int K = 3;
        int[] array = { 2, 5, 4, 7, 8, 9 };
        Console.WriteLine(LongestAlternatingSubarray(array, K)); // Output: 6
    }
}


Javascript




// JavaScript code implementation of the above approach:
function longest_alternating_subarray(arr, K) {
    var n = arr.length;
    var left = 0;
    var max_length = 0;
    var current_length = 1;
    var last_element = arr[0];
     
    // Traversing through array
    for (var right = 1; right < n; right++) {
        // Increase current_length if one or both of last_element and right most element of subarray is odd
        if ((arr[right] % 2 === 0 && last_element % 2 !== 0) || (arr[right] % 2 !== 0 && last_element % 2 === 0)) {
            current_length += 1;
        } else {
            left = right - 1;
            current_length = 1;
        }
        // checking difference between first and last element is at least k
        if (Math.abs(arr[left] - arr[right]) >= K) {
            max_length = Math.max(max_length, current_length);
        }
        last_element = arr[right];
    }
    return max_length;
}
 
// Driver code
var N = 6;
var K = 3;
var array = [2, 5, 4, 7, 8, 9];
console.log(longest_alternating_subarray(array, K));


Output

6






Time complexity: O(N)
Auxiliary space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads