Peaks of a Musical Loop

Time limit2sMemory limit512 MB

Summary
Count local maxima and minima in a circular sequence of samples where consecutive values differ and the first and last differ.
Level

Easy3 of 10

Topics
Implementation, Array, Simulation
Solved
No attempts yet

Problem

A musical loop is a piece of music written to repeat forever: it starts again every time it reaches the end, and no discontinuity is heard at the seam. Loops are common in game audio, especially in casual browser games.

One way to digitize a loop is PCM. PCM, or Pulse Code Modulation, is a technique for representing an analog signal, and it is widely used in digital audio. The technique samples the magnitude of the signal at regular time intervals and stores the sampled values in order. Playback reverses the process (demodulation).

Fernanda works at a game company. She composed a musical loop and encoded it in PCM. While looking at the waveform of her loop in an audio editor, she wanted to count its peaks. A peak of a waveform is a sample value that is a local maximum or a local minimum, that is, a point where the waveform turns around. The figure below shows (a) an example waveform and (b) the loop built from that waveform. The loop in (b) has 48 peaks.

Determine how many peaks Fernanda's musical loop has.

Input

The input contains several test cases. The first line of a test case contains an integer NN, the number of samples in the loop (2≤N≤1042 \le N \le 10^4). The second line contains NN integers H1,H2,…,HNH_1, H_2, \dots, H_N separated by spaces, the magnitudes of the samples (−104≤Hi≤104-10^4 \le H_i \le 10^4, H1≠HNH_1 \ne H_N, and Hi≠Hi+1H_i \ne H_{i+1} for every ii with 1≤i<N1 \le i < N). When the loop plays, H1H_1 follows HNH_N.

The end of the input is a line that contains only the number zero.

Output

For each test case, print one line with a single integer, the number of peaks in Fernanda's musical loop.

Examples5

  1. Example 1

    Input
    2
    1 -3
    6
    40 0 -41 0 41 42
    4
    300 450 449 450
    0
    
    Expected output
    2
    2
    4
    
  2. Example 2

    Input
    2
    5 7
    0
    
    Expected output
    2
    
  3. Example 3

    Input
    2
    -10000 10000
    0
    
    Expected output
    2
    
  4. Example 4

    Input
    5
    1 2 3 4 5
    0
    
    Expected output
    2
    
  5. Example 5

    Input
    6
    1 -1 1 -1 1 -1
    0
    
    Expected output
    6