Problem statement

https://binarysearch.com/problems/Longest-Inequality-Alternating-Sublist/

Solution

Let us evaluate differences between adjacent elements: -1, 0 or 1, depending on sign. Then we split this by 0. We can transfrom it to string and then split it. Or we can use two pointers approach to split. Then for each part evaluate sum of adjacent pairs and look for the biggest amount of adjacent 0, for this we can use groupby.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, A):
        ans = 1
        diff = " ".join([str(int(x<y) - int(y<x)) for x, y in zip(A, A[1:])])
        for part in diff.split("0"):
            vals = [int(i) for i in part.strip().split()]
            if len(vals) >= 1: ans = max(ans, 2)
            diff2 = [x + y for x, y in zip(vals, vals[1:])]
            for i, j in groupby(diff2):
                if i == 0:
                    ans = max(ans, len(list(j)) + 2)
        return ans