Under construction

Still being built. Things may change

Zigzag Histogram Partition

Time limit1sMemory limit1024 MB

Summary
Split a histogram of N bars into contiguous pieces so that each piece's largest rectangle forms a zigzag sequence, maximizing the number of pieces.
Level

Hard8 of 10

Topics
Dynamic programming, Segment tree, Stack
Solved
No attempts yet

Problem

A histogram is formed by placing NN rectangles of width 11 and heights h1h_1, ⋯\cdots, hNh_N in order.

You cut the histogram into several pieces by slicing perpendicular to the base. Each piece must have a positive integer width. When the pieces are listed in order, the largest rectangle area fully contained in each piece forms a zigzag sequence. Maximize the number of pieces.

Formally, a sequence [a1,⋯ ,an][a_1, \cdots, a_n] is a zigzag sequence if it satisfies at least one of the following two conditions.

  • For every 1≤i<n1 \leq i < n, if ii is even then ai≤ai+1a_i \leq a_{i+1}, and if ii is odd then ai≥ai+1a_i \geq a_{i+1}.
  • For every 1≤i<n1 \leq i < n, if ii is even then ai≥ai+1a_i \geq a_{i+1}, and if ii is odd then ai≤ai+1a_i \leq a_{i+1}.

You can transform the histogram with the following operation.

  • Take a strictly increasing sequence [a1,a2,⋯ ,ak+1][a_1, a_2, \cdots, a_{k+1}] with a1=0a_1 = 0 and ak+1=Na_{k+1} = N.
  • The result is a sequence of length kk, written [b1,⋯ ,bk][b_1, \cdots, b_k].
  • For every 1≤i≤k1 \leq i \leq k, bib_i is the largest rectangle area in the histogram formed by joining rectangles ai+1a_i+1 through ai+1a_{i+1} in order.

For every valid sequence [a1,⋯ ,ak+1][a_1, \cdots, a_{k+1}], take the resulting sequence [b1,⋯ ,bk][b_1, \cdots, b_k]. Find the length of the longest one that is a zigzag sequence.

Input

The first line contains a positive integer NN (1≤N≤500 0001 \le N \le 500\,000).

The second line contains NN positive integers h1,⋯ ,hNh_1, \cdots, h_N separated by spaces (1≤hi≤1091 \le h_i \le 10^{9}).

Output

Print the answer on the first line.

Examples1

  1. Example 1

    Input
    5
    3 4 5 6 7
    
    Expected output
    4