Techie Delight
Coding made easy
Longest Alternating Subarray is a problem of finding a subarray with alternating positive and negative elements, and in which the subarray is as long as possible.


The problem differs from problem of finding Longest Alternating Subsequence. Unlike a subsequence, subarray is required to occupy consecutive positions within the original sequences.

For example, consider array { 1, -2, 6, 4, -3, 2, -4, -3 }. The longest alternating subarray is { 4, -3, 2, -4 }. Note that the longest alternating subarray might not be unique.

We can easily solve this problem in linear time using similar logic as kadane’s algorithm. The idea is to maintain longest alternating sub-array “ending” at each index of the given array. This subarray can be single element (if previous element has same sign) or consists of one more elements than the longest alternating subarray ending at the previous index (if previous element has opposite sign).
The algorithm can be implemented as below in C++, Java and Python:

C++

Download   Run Code

Output:

The longest alternating subarray is { 4, -3, 2, -4 }

Java

Download   Run Code

Output:

The longest alternating subarray is [4, -3, 2, -4]

Python

Download   Run Code

Output:

The longest alternating subarray is [4, -3, 2, -4]

Download   Run Code
Output:

The longest alternating subarray is { 4, -3, 2, -4 }

Download   Run Code
Output:

The longest alternating subarray is [4, -3, 2, -4]

Download   Run Code
Output:

The longest alternating subarray is [4, -3, 2, -4]

The time complexity of above solution is O(n) and auxiliary space used by the program is O(1).

Because of the way the algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple example of Dynamic Programming.

source