Under construction

Still being built. Things may change

Zigzag Sequence

Interview

Time limit1sMemory limit1024 MB

Summary
Given a sequence, find the longest contiguous block in which no three consecutive terms are monotone increasing or monotone decreasing.
Level

Medium5 of 10

Topics
Array, Two pointers, Greedy, Implementation
Solved
No attempts yet

Problem

A sequence is a zigzag sequence if nowhere in it do three consecutive terms increase monotonically, and nowhere do three consecutive terms decrease monotonically.

More precisely, a sequence AA of length NN is a zigzag sequence if for every ii with 1≤i≤N−21 \le i \le N-2, neither Ai≤Ai+1≤Ai+2A_i \le A_{i+1} \le A_{i+2} nor Ai≥Ai+1≥Ai+2A_i \ge A_{i+1} \ge A_{i+2} holds.

A sequence AA of length NN is given. Find the maximum length of a contiguous subsequence of AA that is a zigzag sequence.

A sequence BB of length MM is a contiguous subsequence of the sequence AA of length NN when some ii exists with B1=AiB_1 = A_i, B2=Ai+1B_2 = A_{i+1}, ..., BM=Ai+M−1B_M = A_{i+M-1}.

Input

The input consists of two lines. The first line contains the length NN of the sequence.

The second line contains NN integers separated by spaces. The ii-th number is AiA_i.

Output

Print the maximum length of a contiguous subsequence of AA that is a zigzag sequence.

Constraints

  • 3≤N≤50003 \le N \le 5000
  • 1≤Ai≤1091 \le A_i \le 10^9 (1≤i≤N1 \le i \le N)

Examples2

  1. Example 1

    Input
    3
    1 2 3
    
    Expected output
    2
    
  2. Example 2

    Input
    5
    1 3 4 2 5
    
    Expected output
    4