Problem:


Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5



Sample input:
5
1 3 5 4 2


Sample output:
2

Submission status: Accepted

Solution code:
n = int(input())
p = [int(i) for i in input().split()]
c = 0
for i in range(n-2):
    if p[i] < p[i+1] and p[i+1] < p[i+2] or  p[i] > p[i+1] and p[i+1] > p[i+2]:
        c += 1
print(c)

Submission status: Accepted

Solution code:
def solve(N, Ps):
    ans = 0
    for i in range(1, N-1):
        if Ps[i-1] < Ps[i] < Ps[i+1]:
            ans += 1
        if Ps[i-1] > Ps[i] > Ps[i+1]:
            ans += 1
    return ans

if __name__ == "__main__":
    N = int(input())
    Ps = list(map(int, input().split(" ")))
    print(solve(N, Ps))

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
ans = 0
for k in range(1,n-1):
    if p[k-1] < p[k] < p[k+1] or p[k-1] > p[k] > p[k+1]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = [int(i) for i in input().split()]
ans = 0
for i in range(1,n-1):
    if p[i-1]<p[i]<p[i+1] or p[i-1]>p[i]>p[i+1]:  ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
A = [int(x) for x in input().split()]

res = 0
for i in range(1,n-1):
    if A[i-1] < A[i] < A[i+1] or A[i-1] > A[i] > A[i+1]:
        res += 1
print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, P):
    ans = 0
    for i in range(N-2):
        if P[i] < P[i+1] < P[i+2]:
            ans += 1 
        elif P[i] > P[i+1] > P[i+2]:
            ans += 1
            

    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
listP = list(map(int, input().split()))
index=1
counter=0
while index < len(listP)-1:
    if listP[index-1] < listP[index] < listP[index+1]:
        counter+=1
    elif listP[index-1] > listP[index] > listP[index+1]:
        counter += 1
    index+=1
print(counter)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(1, n - 1):
    if p[i - 1] <= p[i] <= p[i + 1] or p[i + 1] <= p[i] <= p[i - 1]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int, input().split()))
ans = 0
for i in range(1, N-1):
  if P[i-1] < P[i] < P[i+1] or P[i-1] > P[i] > P[i+1]:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n = INT()
p = LIST()

ans = 0
for i in range(n):
	if i != 0 and i != n-1 and p[i-1] < p[i] < p[i+1]:
		ans += 1
	elif i != 0 and i != n-1 and p[i-1] > p[i] > p[i+1]:
		ans += 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
p = [int(i) for i in input().split()]

ret = 0
for i in range(0, N - 2) :
    p_ = p[i:i+3]
    if p_[0] < p_[1] < p_[2] or p_[2] < p_[1] < p_[0] :
        ret += 1
        
print(ret)

Submission status: Accepted

Solution code:
n = int(input())
p = [int(i) for i in input().split()]
ans = 0
for i in range(1,n-1):
    if p[i-1]<p[i]<p[i+1] or p[i+1]<p[i]<p[i-1]:
        ans += 1 
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ps = list(map(int, input().split()))

cnt = 0
for i in range(1, n-1):
    mn = min([ps[i-1], ps[i+1]])
    mx = max([ps[i-1], ps[i+1]])
    if ps[i] > mn and ps[i] < mx:
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
p = [int(zz) for zz in input().split()]

ans = 0
for i in range(n-2):
    z = [p[i],p[i+1],p[i+2]]
    if min(z) != z[1] and max(z) != z[1]:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ans = 0

for idx in range(1, n-1):
    if p[idx-1] <= p[idx] <= p[idx+1] or p[idx-1] >= p[idx] >= p[idx+1]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
import bisect
import heapq
import itertools
import math
import os
import re
import string
import sys
from collections import Counter, deque, defaultdict
from decimal import Decimal
from fractions import gcd
from functools import lru_cache, reduce
from operator import itemgetter

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18

N = int(sys.stdin.readline())
P = list(map(int, sys.stdin.readline().split()))


def ok(i):
    return P[i - 1] <= P[i] < P[i + 1] or P[i + 1] <= P[i] < P[i - 1]


ans = 0
for i in range(1, N - 1):
    ans += ok(i)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ans = 0
for i in range(n-2):
    if p[i] < p[i+1] < p[i+2]:
        ans += 1
    if p[i] > p[i+1] > p[i+2]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(1, n - 1):
    if((p[i-1] < p[i] and p[i] < p[i+1]) or (p[i-1] > p[i] and p[i] > p[i+1])):
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ps = list(map(int, input().split()))

cnt = 0
for i in range(n-2):
    if (ps[i] < ps[i+1] < ps[i+2]) or (ps[i] > ps[i+1] > ps[i+2]):
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ret = 0
for i in range(1, n):
    if p[i] != min(p[i - 1:i + 2]) and p[i] != max(p[i - 1:i + 2]):
        ret += 1

print(ret)

Submission status: Accepted

Solution code:
n=int(input())
pl=list(map(int,input().split()))
ans=0
for i in range(1,n-1):
    if pl[i-1]<pl[i]<pl[i+1]:
        ans+=1
    elif  pl[i-1]>pl[i]>pl[i+1]:
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

import random
import collections
import math
import itertools
import bisect

def real_main():
    n = read_int()
    nums = read_int_array()
    ans = sum(nums[i-1] < nums[i] < nums[i+1] or nums[i-1] > nums[i] > nums[i+1] for i in range(1, n-1))
    print(ans)


def solve():
    pass


def main():
    if False and 'PYCHARM_HOSTED' in os.environ:
        main_pycharm()
    else:
        real_main()


from copy import deepcopy
def main_pycharm():
    solution = solve

    test_inputs = None
    test_outputs = None
    judge = None
    slow_solution = None
    if solution is not None:
        if test_outputs is not None:
            test_with_answers(solution, test_inputs, test_outputs)
        if judge is not None:
            test_with_judge(solution, test_inputs, judge)
        if slow_solution is not None:
            test_with_slow_solution(solution, test_inputs, slow_solution)


def test_with_answers(solution, inputs, answers):
    total, wrong = 0, 0
    for args, test_ans in zip(inputs, answers):
        ans = solution(*deepcopy(args))
        if ans != test_ans:
            print('WRONG! ans=%s, test_ans=%s, args=%s' % (ans, test_ans, args))
            wrong += 1
        else:
            print('GOOD')
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))


def test_with_judge(solution, inputs_gen, judge):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))
        if not judge(deepcopy(ans), *deepcopy(args)):
            print('WRONG! ans=%s, args=%s' % (ans, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))


def test_with_slow_solution(solution, inputs_gen, solution_slow):
    total, wrong = 0, 0
    for args in inputs_gen:
        ans = solution(*deepcopy(args))
        slow = solution_slow(*deepcopy(args))
        if ans != slow:
            print('WRONG! ans=%s, slow=%s, args=%s' % (ans, slow, args))
            wrong += 1
        total += 1
    print('ALL %d TESTS PASSED' % total if not wrong else '%d out of %d tests are WRONG' % (wrong, total))

def generate_nums(n, min, max, check_if_good=None):
    while True:
        nums = [random.randint(min, max) for _ in range(n)]
        if check_if_good is None or check_if_good(nums):
            return nums

# This mergesort can be like 7 times faster than build in sort
# (for stupid reasons)
def mergesort(A, key=lambda x: x, reverse=False):
    C = A
    A = list(range(len(A)))
    B = list(A)

    n = len(A)
    for i in range(0, n - 1, 2):
        if key(C[A[i]]) > key(C[A[i ^ 1]]):
            A[i], A[i ^ 1] = A[i ^ 1], A[i]

    width = 2
    while width < n:
        for i in range(0, n, 2 * width):
            R1, R2 = min(i + width, n), min(i + 2 * width, n)
            j, k = R1, i
            while i < R1 and j < R2:
                if key(C[A[i]]) > key(C[A[j]]):
                    B[k] = A[j]
                    j += 1
                else:
                    B[k] = A[i]
                    i += 1
                k += 1
            while i < R1:
                B[k] = A[i]
                k += 1
                i += 1
            while k < R2:
                B[k] = A[k]
                k += 1
        A, B = B, A
        width *= 2

    if reverse:
        A.reverse()
    return A

def mergesort_simple(A, reverse=False):
    C = A
    A = list(range(len(A)))
    B = list(A)

    n = len(A)
    for i in range(0, n - 1, 2):
        if C[A[i]] > C[A[i ^ 1]]:
            A[i], A[i ^ 1] = A[i ^ 1], A[i]

    width = 2
    while width < n:
        for i in range(0, n, 2 * width):
            R1, R2 = min(i + width, n), min(i + 2 * width, n)
            j, k = R1, i
            while i < R1 and j < R2:
                if C[A[i]] > C[A[j]]:
                    B[k] = A[j]
                    j += 1
                else:
                    B[k] = A[i]
                    i += 1
                k += 1
            while i < R1:
                B[k] = A[i]
                k += 1
                i += 1
            while k < R2:
                B[k] = A[k]
                k += 1
        A, B = B, A
        width *= 2

    if reverse:
        A.reverse()
    return A


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

def read():
    return input()

def read_int():
    return int(input())

def read_array(sep=None, maxsplit=-1):
    return input().split(sep, maxsplit)

def read_int_array():
    return [int(a) for a in read_array()]

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-



N = int(input())
Pn = list(map(int, input().split()))
ans = 0
for i in range(1,N-1):
  if Pn[i] == sorted([Pn[i-1],Pn[i],Pn[i+1]])[1]:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ans = 0
for i in range(n-2):
    P = p[i], p[i+1], p[i+2]
    max_P = max(P)
    min_P = min(P)
    if p[i+1] != max_P and p[i+1] != min_P:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N = I()
    P = LI()
    ans = 0
    for i, p in enumerate(P[1:-1], start=1):
        if (P[i - 1] - p) * (P[i + 1] - p) < 0:
            ans += 1
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
nl = lambda: list(map(int, input().split()))
sl = lambda: input().split()
n = lambda: int(input())
s = lambda: input()

N = n()
P = nl()

count = 0
for i in range(1, N-1):
    if P[i-1] <= P[i] and P[i] <= P[i+1]:
        count += 1
    elif P[i-1] >= P[i] and P[i] >= P[i+1]:
        count += 1

print(count)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int, input().split()))

cnt = 0
for i in range(N - 2):
    if P[i+1] != min(P[i:i+3]) and P[i+1] != max(P[i:i+3]):
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
arr=list(map(int,input().split()))
ans=0
for i in range(n-2):
  if arr[i+1]!=min(arr[i:i+3]) and arr[i+1]!=max(arr[i:i+3]):
    ans+=1
print(ans)

Submission status: Accepted

Solution code:
def main():
	N = int(input())
	P = list(map(int, input().split()))
	ans = 0
	for i in range(N-2):
		if P[i] < P[i+1] < P[i+2]:
			ans += 1
		elif P[i+2] < P[i+1] < P[i]:
			ans += 1
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-

def solve():
    n = int(input())
    P = list(map(int, input().split()))

    def f(a, b, c):
        lst = [a, b, c]
        lst.sort()
        if lst[1] == b:
            return True
        return False

    ans = 0
    for i in range(0, n-2):
        if f(P[i], P[i+1], P[i+2]):
            ans += 1
    
    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    P = list(map(int, input().split()))
    ans = 0
    for i in range(1, N-1):
        if P[i-1] < P[i] < P[i+1] or P[i-1] > P[i] > P[i+1]:
            ans += 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
P = [int(x) for x in input().split()]

p0 = P[0]
p1 = P[1]

cnt = 0
for i in range(2, n):
    p2 = P[i]
    if p1 != max(p0, p1, p2) and p1 != min(p0, p1, p2):
        cnt += 1 
    p0, p1 = p1, p2

print(cnt)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#!/usr/bin/env pypy3

from math import *

def main():
    import sys
    sys.dont_write_bytecode = True
    sys.setrecursionlimit(10000000)

    input = sys.stdin.readline

    #import numpy as np
    #import scipy as sp

    # Python 3 modules: https://docs.python.org/3/library/

    import os
    import math, itertools, operator
    from math import factorial as fact
    from operator import itemgetter, attrgetter
    from itertools import permutations, combinations
    from functools import reduce, lru_cache
    # Use scipy for stats: https://docs.scipy.org/doc/scipy/reference/stats.html
    # Before Python 3.5.  Import from math after it.
    from fractions import gcd
    from fractions import Fraction as Frac

    inf = float('inf')

    def lcm(a, b):
        return a * b // gcd(a,b)

    def perm(a, b):
        import scipy.special
        return scipy.special.perm(a, b, exact = True)

    def comb(a, b):
        import scipy.special
        return scipy.special.comb(a, b, exact = True)

    def dfact(n):
        import scipy.special
        return scipy.special.factorial2(n, exact = True)

    def prod(l):
        return reduce(operator.mul, l)

    def input_ints(func = input, sep = None, conv = int):
        return list(map(conv, func().split(sep = sep)))

    if os.environ.get('GOROOT') is None:
        def dprint(*args, **kwargs):
            kwargs['file'] = sys.stderr
            import inspect
            frame = inspect.currentframe().f_back
            print('[' + os.path.basename(frame.f_code.co_filename)
                    + ':' + str(frame.f_lineno) + ']', *args, **kwargs)
    else:
        def dprint(*args, **kwargs):
            pass


    ############################################################################


    n, = list(map(int, input().split()))
    P = input_ints()
    cnt = 0
    for i in range(1, n - 1):
        l = [P[i-1], P[i], P[i+1]]
        l.sort()
        if P[i] == l[1]:
            cnt += 1
    print(cnt)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
arr = list(map(int,input().split()))
ans = 0

for i in range(n-2):
    # print(arr[i], arr[i + 1], arr[i + 2])
    if (arr[i] < arr[i+1] and arr[i+1] < arr[i+2]) or (arr[i] > arr[i+1] and arr[i+1] > arr[i+2]):

        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
P = list(map(int, input().split()))
ans = 0
for i in range(n-2):
    if P[i] <= P[i+1] <= P[i+2] or P[i] >= P[i+1] >= P[i+2]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ans = 0
for i in range(n - 2):
    if max(p[i:i + 3]) != p[i + 1] and min(p[i:i + 3]) != p[i + 1]:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))

ans = 0
for i in range(1,n-1):
    if p[i-1] < p[i] < p[i+1]: ans += 1
    if p[i-1] > p[i] > p[i+1]: ans += 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))

ans = 0
for a,b,c in zip(P,P[1:],P[2:]):
    if a<b<c or c<b<a:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
import math
import fractions
import copy
import numpy as np
def j(q):
    if q==1: print("Yes")
    elif q == 0:print("No")
    exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def iprow():
    return [int(i) for i in input().split()]
def ips():
    return (int(i) for i in input().split())
def printrow(a):
    for i in a:
        print(i)
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

#n,m = ips()
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(m)]    #入力セット(整数改行あり)(2/2)
#a=[input() for i in range(n)]    #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#a.pop(0)は10^5あるときTLEしやすい!注意!抜くなら逆ソート!
n = ip()
a = iprow()
b =[]
s =0
for i in range(n-2):
    b = a[i:(i+3)]
    if b[1] != min(b) and b[1] != max(b):
        s+=1
print(s)

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, ceil, floor
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
import heapq
INF = float("inf")
sys.setrecursionlimit(10**7)
# 4近傍（右, 下, 左, 上）
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
def inside(y: int, x: int, H: int, W: int) -> bool: return 0 <= y < H and 0 <= x < W
def mi(): return map(int, input().split())
def ii(): return int(input())
###template###

n = ii()
Ps = list(mi())

ans = 0
for i in range(1, n-1): #1~n-2について確認
  if sorted([Ps[i-1],Ps[i],Ps[i+1]])[1] == Ps[i]:
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
P = [int(i) for i in input().split()]

count = 0
for i in range(1, N - 1):
    if P[i - 1] < P[i] < P[i + 1] or P[i + 1] < P[i] < P[i - 1]:
        count += 1
print(count)

Submission status: Accepted

Solution code:
n = int(input())
p=list(map(int, input().split()))
cnt = 0
for i in range(n-2):
    if (p[i] > p[i+1] and p[i+1] > p[i+2]) or (p[i] < p[i+1] and p[i+1] < p[i+2]):
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n = ni()
a = na()
ct = 0
for i in range(n-2):
    if a[i] <= a[i+1] <= a[i+2] or a[i+2] <= a[i+1] <= a[i]:
        ct += 1
print(ct)

Submission status: Accepted

Solution code:
n = int(input())
P = list(map(int, input().split()))

res = 0
for i in range(n-2):
    if (P[i] < P[i+1] < P[i+2]) or (P[i+2] < P[i+1] < P[i]):
        res += 1
        
print(res)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(1, n-1):
  if p[i-1]<p[i]<p[i+1] or p[i+1]<p[i]<p[i-1]:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    s = S()
    d = defaultdict(int)
    for i in s:
        d[i] += 1
    for i in d.keys():
        if d[i] != 2:
            print("No")
            quit()
    print("Yes")
    return

#B
def B():
    n = I()
    p = LI()
    ans = 0
    for i in range(1,n-1):
        k = p[i-1:i+2]
        k.sort()
        if k[1] == p[i]:
            ans += 1
    print(ans)
    return

#C
def C():
    n = I()

    return

#D
def D():
    n = I()

    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return


#Solve
if __name__ == "__main__":
    B()

Submission status: Accepted

Solution code:
n=int(input())
p=[int(i) for i in input().split()]
ans=0
for i in range(1,n-1):
    a,b,c=p[i-1],p[i],p[i+1]
    if a<b<c or a>b>c:
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(n: int, p: "List[int]"):

    counter = 0
    for i in range(n-2):
        if p[i] < p[i+1] < p[i+2]:
            counter += 1
        elif p[i+2] < p[i+1] < p[i]:
            counter += 1
    print(counter)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    n = int(next(tokens))  # type: int
    p = [int(next(tokens)) for _ in range(n)]  # type: "List[int]"
    solve(n, p)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n-2):
  b = a[i:i+3]
  c = sorted(b)
  if b[1] == c[1]:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(1,n-1):
    if (a[i-1] < a[i] < a[i+1]) or (a[i-1] > a[i] > a[i+1]):
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
*p, = map(int, input().split())
ans = 0
for i in range(n - 2):
	if p[i] < p[i + 1] < p[i + 2] or p[i + 2] < p[i + 1]< p[i]:
		ans += 1
print(ans)

Submission status: Accepted

Solution code:
#import sys
#input = sys.stdin.readline
def main():
    n = int( input())
    P = list( map( int, input().split()))
    ans = 0
    for i in range(1, n-1):
        if P[i-1] < P[i] and P[i] < P[i+1]:
            ans += 1
        elif P[i-1] > P[i] and P[i] > P[i+1]:
            ans += 1
    print(ans)
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N = inp()
pp = inpl()
ans = 0
for i in range(N-2):
    a,b,c = pp[i:i+3]
    if a < b < c or c < b < a:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))

ans = 0
for i in range(n-2):
    l = [p[i], p[i+1], p[i+2]]
    l.sort()
    if l[1] == p[i+1]:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
#n,k=map(int,input().split())
a=list(map(int,input().split()))
ans=0
for i in range(1,n-1):
  b=[a[i-1],a[i],a[i+1]]
  b.sort()
  if b[1]==a[i]:ans+=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
*A, = map(int, input().split())
ans = 0
for i in range(1, N-1):
    if sorted(A[i-1:i+2])[1] == A[i]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
res = 0
for i in range(n - 2):
    a,b,c = p[i],p[i+1],p[i+2]
    if a<b<c or a>b>c:
        res += 1
print(res)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(1, n - 1):
    if a[i - 1] < a[i] < a[i + 1] or a[i - 1] > a[i] > a[i + 1]:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8

n = int(input())
p = list(map(int, input().split()))

cnt = 0
for i in range(1, n-1):
    if p[i-1] < p[i] < p[i+1] or p[i+1] < p[i] < p[i-1]:
        cnt += 1

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(1, n-1):
    p1, p2, p3 = p[i-1], p[i], p[i+1]
    if p1 < p2 < p3 or p3 < p2 < p1:
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
ans = 0
for i in range(n):
    if i>=1 and i <n-1:
        if (p[i-1]<p[i] and p[i] < p[i+1]) or (p[i-1]>p[i] and p[i] > p[i+1]):
            ans += 1

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as ite
import sys
import math

sys.setrecursionlimit(1000000)

INF = 10 ** 18
MOD = 10 ** 9 + 7

N = input()
p = map(int, raw_input().split())
ans = 0
for i in range(1, N - 1):
    if p[i - 1] < p[i] < p[i + 1] or p[i + 1] < p[i] < p[i - 1]:
        ans += 1
print ans

Submission status: Accepted

Solution code:
def inpl():
    return list(map(int, input().split()))


n = int(input())
P = inpl()

ans = 0
for a, b, c in zip(P, P[1:], P[2:]):
    if max(a, c) > b and min(a, c) < b:
        ans += 1

print(ans)