Longest alternating Subarray with absolute difference at least K
Last Updated :
19 Oct, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int longest_alternating_subarray( int arr[], int n, int k)
{
int max_length = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if ( abs (arr[i] - arr[j]) < k) {
continue ;
}
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) {
max_length = length;
}
}
}
}
return max_length;
}
int main()
{
int arr[] = { 2, 5, 4, 7, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
int length = longest_alternating_subarray(arr, n, k);
cout << length << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int
longest_alternating_subarray( int arr[], int n, int k)
{
int max_length = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (Math.abs(arr[i] - arr[j]) < k) {
continue ;
}
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) {
max_length = length;
}
}
}
}
return max_length;
}
public static void main(String[] args)
{
int arr[] = { 2 , 5 , 4 , 7 , 8 , 9 };
int n = arr.length;
int k = 3 ;
int length
= longest_alternating_subarray(arr, n, k);
System.out.println(length);
}
}
|
Python3
import math
def longest_alternating_subarray(arr, n, k):
max_length = 0
for i in range (n):
for j in range (i + 1 , n):
if abs (arr[i] - arr[j]) < k:
continue
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:
max_length = length
return max_length
arr = [ 2 , 5 , 4 , 7 , 8 , 9 ]
n = len (arr)
k = 3
length = longest_alternating_subarray(arr, n, k)
print (length)
|
C#
using System;
class GFG {
public static int
longest_alternating_subarray( int [] arr, int n, int k)
{
int max_length = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (Math.Abs(arr[i] - arr[j]) < k) {
continue ;
}
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) {
max_length = length;
}
}
}
}
return max_length;
}
public static void Main()
{
int [] arr = { 2, 5, 4, 7, 8, 9 };
int n = arr.Length;
int k = 3;
int length
= longest_alternating_subarray(arr, n, k);
Console.WriteLine(length);
}
}
|
Javascript
function longestAlternatingSubarray(arr, n, k) {
let maxLength = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (Math.abs(arr[i] - arr[j]) < k) {
continue ;
}
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) {
maxLength = length;
}
}
}
}
return maxLength;
}
const arr = [2, 5, 4, 7, 8, 9];
const n = arr.length;
const k = 3;
const length = longestAlternatingSubarray(arr, n, k);
console.log(length);
|
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>
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];
for ( int right = 1; right < n; right++) {
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;
}
if (std:: abs (arr[left] - arr[right]) >= K) {
max_length = std::max(max_length, current_length);
}
last_element = arr[right];
}
return max_length;
}
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 {
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 );
for ( int right = 1 ; right < n; right++) {
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 ;
}
if (Math.abs(arr.get(left) - arr.get(right)) >= K) {
maxLength = Math.max(maxLength, currentLength);
}
lastElement = arr.get(right);
}
return maxLength;
}
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
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
N = 6
K = 3
array = [ 2 , 5 , 4 , 7 , 8 , 9 ]
print (longest_alternating_subarray(array, K))
|
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];
for ( int right = 1; right < n; right++)
{
if ((arr[right] % 2 == 0 && lastElement % 2 != 0) ||
(arr[right] % 2 != 0 && lastElement % 2 == 0))
{
currentLength += 1;
}
else
{
left = right - 1;
currentLength = 1;
}
if (Math.Abs(arr[left] - arr[right]) >= K)
{
maxLength = Math.Max(maxLength, currentLength);
}
lastElement = arr[right];
}
return maxLength;
}
public static void Main( string [] args)
{
int K = 3;
int [] array = { 2, 5, 4, 7, 8, 9 };
Console.WriteLine(LongestAlternatingSubarray(array, K));
}
}
|
Javascript
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];
for ( var right = 1; right < n; right++) {
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;
}
if (Math.abs(arr[left] - arr[right]) >= K) {
max_length = Math.max(max_length, current_length);
}
last_element = arr[right];
}
return max_length;
}
var N = 6;
var K = 3;
var array = [2, 5, 4, 7, 8, 9];
console.log(longest_alternating_subarray(array, K));
|
Time complexity: O(N)
Auxiliary space: O(1)
Similar Reads
Longest subarray with absolute difference between any pair at most X
Given an integer array arr[] of size n and an integer x, the task is to find the longest sub-array where the absolute difference between any two elements is not greater than x. Examples: Input: arr[] = [ 8, 4, 2, 6, 7 ], x = 4 Output: [ 4, 2, 6 ] Explanation: The sub-array described by index [1, 3],
15+ min read
Length of the longest alternating increasing decreasing subarray
Given an array arr[], the task is to find the length of the longest alternating subarray. A subarray {x1, x2, .. xn} is an alternating increasing decreasing sequence if its elements satisfy one of the following relations : x1 < x2 > x3 < x4 > x5 < â¦. xn or x1 > x2 < x3 > x4
15+ min read
Longest Subarray with sum differences ⤠K
Given a sorted array arr[] of size N, the task is to find the length of the longest subarray and print the subarray such that the sum of the differences of the maximum element of the chosen subarray with all other elements of that same subarray is ⤠K.i.e. â(amax-ai) ⤠K, for that given subarray. Ex
7 min read
Length of Longest Subarray with same elements in atmost K increments
Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments. Examples: Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as
15+ min read
Longest subarray with difference exactly K between any two distinct values
Given an array arr[] of length N and an integer K, the task is to find the longest subarray with difference between any two distinct values equal to K. Print the length of the longest subarray obtained. Otherwise, if no such subarray is obtained, print -1. Examples: Input: arr[] = {0, 0, 1, 1, 3, 3,
12 min read
Count of subarrays of size K having at least one pair with absolute difference divisible by K-1
Given an arr[] consisting of N elements, the task is to count all subarrays of size K having atleast one pair whose absolute difference is divisible by K - 1.Examples: Input: arr[] = {1, 5, 3, 2, 17, 18}, K = 4 Output: 3 Explanation: The three subarrays of size 4 are: {1, 5, 3, 2}: Pair {5, 2} have
4 min read
Maximum absolute difference between sum of subarrays of size K
Given an array arr[] of size N and an integer K, the task is to find maximum absolute difference between the sum of subarrays of size K.Examples : Input: arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}, K = 3 Output: 6 Explanation:: Sum of subarray (-2, -3, 4) = -1 Sum of subarray (-3, 4, -1) = 0 Sum of subar
13 min read
Split array into K subarrays with minimum sum of absolute difference between adjacent elements
Given an array, arr[] of size N and an integer K, the task is to split the array into K subarrays minimizing the sum of absolute difference between adjacent elements of each subarray. Examples: Input: arr[] = {1, 3, -2, 5, -1}, K = 2Output: 13Explanation: Split the array into following 2 subarrays:
8 min read
Longest Increasing subarray with one change allowed
Given an array, find the length of the longest increasing subarray (contiguous elements) such that it is possible to change at most one number (change one number to any integer you want) from the sequence to make the sequence strictly increasing. Examples: Input : 6 7 2 3 1 5 10 Output : 5 Explanati
7 min read
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 i
5 min read