Problem:


Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3



Sample input:
6
1 2 3 2 2 1


Sample output:
2

Submission status: Accepted

Solution code:
import sys

read= sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
MOD = 1000000007
sys.setrecursionlimit(10**7)

#N,*A = map(int,read().split())
N = int(input())
A = list(map(int,input().split()))

#現在作ってる数列の種類を記録
# 単調増加：1
# 単調減少 ：-1
# 初期値:0
State = 0

#答え入れる
res = 1

for i in range(1,N):
    
    #A[i]はA[i-1]と比べたときの大小を記録

    #X に現在の状態を記録
    # 増加：1
    # 減少 ：-1
    # 同じ値:0
    if A[i] > A[i-1]: #大きくなった時
        X = 1 
    elif A[i] == A[i-1]: #等しい時
        X = 0
    else :# それ以外(小さくなった時)
        X = -1

    #現在の状態と作っている数列の状態が同じとき
    if X == State:
        continue
    
    #配列の種類が0の時(どちらにもなりえる)
    if  State == 0: 
        State = X #Stateが決定されるため、更新

    #現在の状態と作っている数列の状態が違い、現在の状態が0出ないとき
    if X != State  and  X != 0: 
        res += 1 
        State = 0 #数列を初期化

print(res)

Submission status: Accepted

Solution code:
import sys

read= sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
MOD = 1000000007
sys.setrecursionlimit(10**7)

#N,*A = map(int,read().split())
N = int(input())
A = list(map(int,input().split()))

State = 0
res = 1

for i in range(1,N):
    if A[i] > A[i-1]:
        X = 1
    elif A[i] == A[i-1]:
        X = 0
    else :
        X = -1

    #前と同じ状態の時
    if X == State:
        continue
    
    if  State == 0:
        State = X

    if X != State  and  X != 0:
        res += 1
        State = 0

print(res)

Submission status: Accepted

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

ans = 1
sq = 0
a = A[0]
for i in range(1,n):
    #print(a,A[i], sq)
    if sq == 0 and A[i] < a:
        sq = -1
    elif sq == 0 and A[i] > a:
        sq = 1
    elif (sq == 1 and A[i] < a) or (sq == -1 and A[i] > a):
        #print('---')
        ans += 1
        sq = 0
    a = A[i]

print(ans)

Submission status: Accepted

Solution code:
import sys

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


ans = 1
state = -1
for i in range(1, N):
    if state == -1:
        if A[i] < A[i-1]:
            state = 0
        elif A[i] > A[i-1]:
            state = 1
    elif (state == 0 and A[i] > A[i-1]) or (state == 1 and A[i] < A[i-1]):
        ans += 1
        state = -1
 
print(ans)

Submission status: Accepted

Solution code:
import sys

read= sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
MOD = 1000000007
sys.setrecursionlimit(10**7)

#N,*A = map(int,read().split())
N = int(input())
l = list(map(int,input().split()))

#最初の状態分を加算するため、1からカウント
ans = 1

S = 0 #現在の状態 増加 or 減少 or 初期化

for i in range(1,N):
    X = l[i] - l[i-1]

    X = 0 if X == 0 else 1 if X > 0 else -1

    #同じ値の時l[i] == l[i-1]
    if X == 0:
        continue

    #Stateが初期のときは現在の状態に更新
    elif S == 0:
        S = X

    #Stateが違うときは答えに加算して、Stateを初期値に
    elif S != X:
        ans += 1
        S = 0

print(ans)

Submission status: Accepted

Solution code:
N= int(input())
now=0
ans=1
S=0
l=list(map(int,input().split()))
for i in range(1,N):
   X=l[i]-l[i-1]
   X=0 if X==0 else 1 if X>0 else -1
   if X==0:
      continue
   elif S ==0:
      S=X
   elif S != X:
      ans+=1
      S=0
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
n=int(input())
a=list(map(int,input().split()))
d=deque(a)
tmp=[d[0]]
d.popleft()
ans=1
while d:
    t=tmp[-1]-tmp[0]
    if len(tmp)==1 or t==0:
        tmp.append(d.popleft())
    elif t>0 and d[0]>=tmp[-1]:
        tmp.append(d.popleft())
    elif t<0 and d[0]<=tmp[-1]:
        tmp.append(d.popleft())
    else:
        ans+=1
        tmp=[d.popleft()]
print(ans)

Submission status: Accepted

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

dp = [[N, N] for i in range(N)]
dp[0] = [1, 1]
for i, a in enumerate(A[1:], 1):
  pre_a = A[i-1]
  if pre_a < a:
    dp[i][0] = min(dp[i-1][0], dp[i-1][1]+1)
    dp[i][1] = min(dp[i-1][0]+1, dp[i-1][1]+1)
  elif pre_a == a:
    dp[i][0] = min(dp[i-1][0], dp[i-1][1]+1)
    dp[i][1] = min(dp[i-1][0]+1, dp[i-1][1])
  else:
    dp[i][0] = min(dp[i-1][0]+1, dp[i-1][1]+1)
    dp[i][1] = min(dp[i-1][0]+1, dp[i-1][1])

print(min(dp[-1]))

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
if N == 1:
    print(1)
    quit()

A.append(A[N-1])
ans = 1
last = A[0]
s = 0
for i in range(N-1):
    if not(A[s] <= A[i] <= A[i+1]) and not(A[s] >= A[i] >= A[i+1]):
        s = i + 1
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
def answer(arr):
    n = len(arr)
    count = 0
    INC = 'INCREASING'
    DEC = 'DECREASING'
    STATE = None
    if n == 1 or n == 2:
        return 1
    for i in range(n-1):
        diff = arr[i+1] - arr[i]
        if diff == 0:
            continue
        if STATE is None:
            if diff > 0:
                STATE = INC
            if diff < 0:
                STATE = DEC
            count += 1
        elif STATE is INC:
            if diff < 0:
                STATE = None
        elif STATE is DEC:
            if diff > 0:
                STATE = None
        if STATE is None and i == n-2:
            count += 1
            
    return count

n = int(input())
arr = list(map(int, input().split()))
print(answer(arr))

Submission status: Accepted

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

if n == 1:
    print(1)
    exit()

d = [0] * (n - 1)
if (L[0] > L[1]):
    d[0] = -1
elif (L[0] < L[1]):
    d[0] = 1

for i in range(n):
    if (i == 0):
        continue
    elif (i == n - 1):
        break
    else:
        if (L[i] < L[i + 1]):
            d[i] = 1
        elif (L[i] > L[i + 1]):
            d[i] = -1

prev = 0
count = 0
for i in range(len(d)):
    if (i == 0):
        prev = d[i]
        continue
    if (prev == 1):
        if (d[i] == 1):
            continue
        elif (d[i] == 0):
            continue
        else:
            count += 1
            prev = 0
    elif (prev == -1):
        if (d[i] == -1):
            continue
        elif (d[i] == 0):
            continue
        else:
            count += 1
            prev = 0
    elif (prev == 0):
        if (d[i] == 1):
            prev = 1
        elif (d[i] == -1):
            prev = -1

print(count + 1)

Submission status: Accepted

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

state = -1
res = 1
for i in range(1, n):
    if state == -1:
        if a[i] < a[i-1]:
            state = 0
        elif a[i] > a[i-1]:
            state = 1
    elif (state == 0 and a[i] > a[i-1]) or (state == 1 and a[i] < a[i-1]):
        res += 1
        state = -1

print(res)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
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()
    A=LI()
    now = []
    increase_status = 0
    INCREASE = 0
    DECREASE = 1
    NOTDEFINE = 2

    ans = 0
    for a in A:
        if(now):
            if(increase_status == INCREASE):
                if(now<=a):
                    now = a
                else:
                    ans += 1
                    now = a
                    increase_status = NOTDEFINE
            elif(increase_status == DECREASE):
                if(now>=a):
                    now = a
                else:
                    ans += 1
                    now = a
                    increase_status = NOTDEFINE
            else:
                if(now>a):
                    increase_status = DECREASE
                elif(now<a):
                    increase_status = INCREASE
                now = a

        else:
            now = a
            ans += 1
            increase_status = NOTDEFINE
    print(ans)
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
a.append(a[n - 1])
ans = 1
s = 0
i = 1
while i < n:
    if not(a[s] <= a[i] <= a[i + 1]) and not(a[s] >= a[i] >= a[i + 1]):
        s = i + 1
        ans += 1
    i += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    n=int(input())
    l=list(map(int,input().split()))
    prev='ryouhou'
    cnt=0
    for i in range(n-1):
        if l[i+1]-l[i]>0:
            if prev=='-':
                cnt+=1
                prev='ryouhou'
            else:
                prev='+'
        elif l[i+1]-l[i]<0:
            if prev=='+':
                cnt+=1
                prev='ryouhou'
            else:
                prev='-'
    print(cnt+1)
resolve()

Submission status: Accepted

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

count = 1
up,down = 1,1

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

print(count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
l = list(map(int,input().split()))
left = 0
right = 1
cou = 0
f = 2
while right!=n and right!=n+1:
  if l[left]==l[right]:
    left += 1
    right += 1
  elif l[left]<l[right]:
    while right!=n and l[left]<=l[right]:
      left += 1
      right += 1
    cou += 1
    left +=1
    right += 1
    f = 1
  else:
    while right!=n and l[left]>=l[right]:
      left += 1
      right += 1
    cou += 1
    left += 1
    right += 1
    f = 0
if f==2:
  cou += 1
elif f==1 and l[-2]>l[-1]:
  cou += 1
elif f==0 and l[-2]<l[-1]:
  cou += 1
print(cou)

Submission status: Accepted

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

prev = A[0]
isUp = True
isDown = True

ans = 0
for a in A[1:]:
  if prev == a:
    pass
  elif prev < a:
    isDown = False
    if not isUp:
      isUp = True
      isDown = True
      ans += 1
  elif a < prev:
    isUp = False
    if not isDown:
      isUp = True
      isDown = True
      ans += 1
      
  prev = a
  
print(ans+1)

Submission status: Accepted

Solution code:
n, *a_l = map(int, open(0).read().split())
before = a_l[0]
not_decrease, not_increase = False, False
cnt = 1
for a in a_l:
    if not_decrease:
        if before > a:
            cnt += 1
            not_decrease = False
    elif not_increase:
        if before < a:
            cnt += 1
            not_increase = False
    else:
        if before == a:
            continue
        elif before < a:
            not_decrease = True
        else:
            not_increase = True
    before = a
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
L = list(map(int, input().split()))
cnt = 1
state = None
i = 1
while i < n:
    if state is None:
        if L[i] > L[i - 1]:
            state = 'up'
        elif L[i] < L[i - 1]:
            state = 'down'
        i += 1
    else:
        if state == 'up':
            while L[i] >= L[i - 1]:
                i += 1
                if i >= n - 1:
                    print(cnt)
                    exit()
            cnt += 1
            i += 1
            state = None
        else:
            while L[i] <= L[i - 1]:
                i += 1
                if i >= n - 1:
                    print(cnt)
                    exit()
            cnt += 1
            i += 1
            state = None
print(cnt)

Submission status: Accepted

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

prev = A[0]
ans = 1
for i in range(1, N):
    if A[i] > prev:
        pls = "plus"
        break
    elif A[i] < prev:
        pls = "minus"
        break
else:
    print(1)
    exit()

for i in range(1, N):
    if pls == "plus" and prev > A[i]:
        prev = A[i]
        ans += 1
        pls = "even"
        continue
    if pls == "minus" and prev < A[i]:
        prev = A[i]
        ans += 1
        pls = "even"
        continue
    if pls == "even" and prev < A[i]:
        pls = "plus"
    elif pls == "even" and prev > A[i]:
        pls = "minus"
    prev = A[i]
print(ans)

Submission status: Accepted

Solution code:
def resolve():
    # 整数 1 つ
    n = int(input())
    # 整数複数個
    # a, b = map(int, input().split())
    # 整数 N 個 (改行区切り)
    # N = [int(input()) for i in range(N)]
    # 整数 N 個 (スペース区切り)
    A = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    # A = [list(map(int, input().split())) for i in range(H)]

    result = 0
    while len(A) > 1:
        flag = False
        for i in range(1, len(A)):
            if A[0] == A[i]:
                continue
            elif A[0] < A[i]:
                j = i
                while A[j-1] <= A[j]:
                    j += 1
                    if j == len(A):
                        A = []
                        result += 1
                        flag = True
                        break
                else:
                    del A[:j]
                    result += 1
                    flag = True
            elif A[0] > A[i]:
                j = i
                while A[j-1] >= A[j]:
                    j += 1
                    if j == len(A):
                        A = []
                        result += 1
                        flag = True
                        break
                else:
                    del A[:j]
                    result += 1
                    flag = True
            if flag == True:
                break
    else:
        if len(A) == 1:
            result += 1
    print(result)

resolve()

Submission status: Accepted

Solution code:
n = int(input())
num_list = [int(i) for i in input().split()]
if len(num_list)==1:
  print(1)
else:
  res = 1
  flag = None
  pre = num_list[0]
  for i in num_list[1:]:
    if pre > i and not flag:
      flag = 'down'
  
    elif pre < i and not flag:
      flag = 'up'
      
    elif (pre > i and flag=='up') or (pre < i and flag=='down'):
      res += 1
      flag = None
    pre = i
  print(res)

Submission status: Accepted

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

#左から丹頂非増加、単調非減少を試して行って長い方を採用すれば良いO(N)
#値の増減の反転するポイントを探索する

ans = 1
tmp = 0
for i in range(1, n):
    if (A[i] - A[i-1]) * tmp < 0:
        ans += 1
        tmp = 0
    elif A[i] - A[i-1] != 0:
        tmp = A[i] - A[i-1]

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))

if N <= 2:
    print(1)
    sys.exit()

A = [A[0]] + [y for x,y in zip(A,A[1:]) if x != y]
sq = np.diff(A)

ans = 1
flg = 0
prev = sq[0]
for i in range(1, len(sq)):
    if flg==1:
        prev = sq[i]
        flg = 0
        continue
    current = sq[i]
    if (prev * current) > 0:
        continue
    else:
        ans += 1
        prev = current
        flg = 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
c = 1
i = 0
while i < N - 1:
    if A[i] < A[i + 1]:
        while True:
            i += 1
            if i == N - 1:
                break
            if A[i] > A[i + 1]:
                c += 1
                i += 1
                break
    elif A[i] > A[i + 1]:
        while True:
            i += 1
            if i == N - 1:
                break
            if A[i] < A[i + 1]:
                c += 1
                i += 1
                break
    elif A[i] == A[i + 1]:
        i += 1
print(c)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
if(N == 1):
    print(1)
    exit(0)
cur = A[0]
# 昇順(1)か降順(0)かのフラグ
ans = 1
flag = -1
for i in range(1, N):
    if(cur == A[i]): continue
    if(flag == -1):
        if(A[i] > cur): flag = 1
        elif(A[i] < cur): flag = 0
    elif(flag == 1 and A[i] < cur):
        flag = -1
        ans += 1
    elif(flag == 0 and A[i] > cur):
        flag = -1
        ans += 1
    cur = A[i]
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
if(N == 1):
    print(1)
    exit(0)
cur = A[0]
# 昇順(1)か降順(0)かのフラグ
ans = 1
flag = -1
for i in range(1, N):
    if(cur == A[i]): continue
    if(flag == -1):
        if(A[i] > cur): flag = 1
        elif(A[i] < cur): flag = 0
        cur = A[i]
        continue
    if(flag == 1 and A[i] < cur):
        cur, flag = A[i], -1
        ans += 1
        continue
    if(flag == 1 and A[i] > cur):
        cur = A[i]
        continue
    if(flag == 0 and A[i] > cur):
        cur, flag = A[i], -1
        ans += 1
        continue
    if(flag == 0 and A[i] < cur):
        cur = A[i]
        continue
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
if N == 1:print(1);exit()
A = [int(hoge) for hoge in input().split()]
ans = 1
cur = A[0]
Decided = A[0] != A[1]
Flat = A[0] == A[1]
Up = A[0] < A[1]

for n in range(1,N):
    if Decided:
        if A[n] == cur:
            continue
        if (A[n]>=cur) == Up:#数列が続く
            cur = A[n]
        else:
            cur = A[n]
            Up = 1 - Up
            Decided = False
            ans += 1
    else:
        if A[n] != cur:
            Up = A[n] > cur
            cur = A[n]
            Decided = True
print(ans)

Submission status: Accepted

Solution code:
"""
覚えておきたい
"""

n,*a=map(int,open(0).read().split())
ans=1
tmp=0
for i in range(1,n):
  if (a[i]-a[i-1])*tmp<0:
    ans+=1
    tmp=0
  elif not a[i]-a[i-1]==0:
    tmp=a[i]-a[i-1]
print(ans)

Submission status: Accepted

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

count = 1
state = ""
for i in range(N-1):
    if A[i] > A[i+1] and state == "":
        state = "minus"
    elif A[i] > A[i+1] and state == "plus":
        state = ""
        count += 1
    elif A[i] > A[i+1] and state == "minus":
        continue
    elif A[i] < A[i+1] and state == "":
        state = "plus"
    elif A[i] < A[i+1] and state == "minus":
        state = ""
        count += 1
    elif A[i] < A[i+1] and state == "plus":
        continue
    else:
        continue
print(count)

Submission status: Accepted

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

num = 1
flag = -1 # -1:initial, 0:increasing, 1:decreasing
for i in range(1,n):
    if a_l[i] > a_l[i-1]:
        new_flag = 0
    elif a_l[i] < a_l[i-1]:
        new_flag = 1
    else:
        continue
    if new_flag != flag:
        if flag == -1:
            flag = new_flag
        else:
            flag = -1
            num += 1

print(max(num,1))

Submission status: Accepted

Solution code:
n,*a=map(int,open(0).read().split())
ans=1
tmp=0
for i in range(1,n):
  if (a[i]-a[i-1])*tmp<0:
    ans+=1
    tmp=0
  elif not a[i]-a[i-1]==0:
    tmp=a[i]-a[i-1]
print(ans)

Submission status: Accepted

Solution code:
# A - Sorted Arrays
import numpy as np

N = int(input())
A = list(map(int, input().split()))
sgn = 0
ans = 1

for i in range(N-1):
    tmp = np.sign(A[i+1]-A[i])
    if tmp*sgn<0:
        ans += 1
        sgn = 0
    else:
        sgn = np.sign(2*sgn+tmp)

print(ans)

Submission status: Accepted

Solution code:
import math
import queue
from collections import defaultdict
 
def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):#階乗
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):#コンビネーション
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def printQueue(q):
	r=qb
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
def dq():
	return queue.deque()
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): # root
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): # much time
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} # 1~n
def bitArr(n):#ビット全探索
	x = 1
	zero = "0"*n
	ans = []
	ans.append([0]*n)
	for i in range(2**n-1):
		ans.append(list(map(lambda x:int(x),list((zero+bin(x)[2:])[-1*n:]))))
		x+=1
	return ans;
def arrsSum(a1,a2):
	for i in range(len(a1)):
		a1[i]+=a2[i]
	return a1
def maxValue(a,b,v):
	v2 = v
	for i in range(v2,-1,-1):
		for j in range(v2//a+1): #j:aの個数
			k = i-a*j
			if k%b==0:
				return i
	return -1

n = readInt()
a = readInts()

ans = 1

i = 0

def plumin(i):
	if a[i+1]-a[i]>0:
		return 1
	elif a[i+1]-a[i]<0:
		return -1
	else:
		return 0

pmarr = []
for i in range(n-1):
	x = plumin(i)
	if x!=0:
		pmarr.append(x)

#print(pmarr)
if len(pmarr)==0:
	print(ans)
	exit()
be = pmarr[0]
for i in range(1,len(pmarr)):
	if pmarr[i]==be:
		continue
	else:
		ans+=1
		if i+1==len(pmarr):
			break
		be = pmarr[i+1]

print(ans)

Submission status: Accepted

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

#左から単調非増加、単調非減少を試して行って長いほうを採用すればよいO(N)
#値の増減の反転するポイントを探索する
ans=1
tmp=0
for i in range(1,n):
    if (a_input[i]-a_input[i-1])*tmp<0:
        ans+=1
        tmp=0
    elif a_input[i]-a_input[i-1]!=0:
        tmp=a_input[i]-a_input[i-1]

print(ans)

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import decimal
import bisect
import itertools
import fractions
import functools
import copy

# import heapq
# from collections import deque
# import decimal

sys.setrecursionlimit(10000001)
INF = sys.maxsize
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))

# ===CODE===
tMOD = 998244353


def main():
    n = ni()
    a = na()

    tmp = []
    state = 0
    ans = 0
    for i in range(n):
        if len(tmp) < 1:
            hoge=0
        else:
            current_state = a[i]-tmp[-1]
            if current_state == 0:
                hoge=0
            elif state == 0:
                if current_state > 0:
                    state = 1
                else:
                    state = -1
            elif state * current_state < 0:
                tmp.clear()
                ans += 1
                state=0
        tmp.append(a[i])

    print(ans+1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
zougen = 4 #0は変化無し、1は減少、２は増加、4は未決定
ans=1
for i in range(N-1):
    if zougen==4:
        if A[i]-A[i+1]<0:
            zougen = 2
        elif A[i]-A[i+1]>0:
            zougen = 1
        else:
            zougen =0
    if A[i]-A[i+1]<0:
        if zougen == 1:
            ans+=1
            zougen=4
        if zougen == 0:
            zougen =2
    if A[i]-A[i+1]>0:
        if zougen == 2:
            ans+=1
            zougen=4
        if zougen ==0:
            zougen = 1
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = list(map(int, input().split()))

    op = None
    prev = A[0]
    cnt = 0
    for i in range(1, N):
        if op is None:
            if prev == A[i]:
                continue
            elif prev < A[i]:
                op = "up"
                prev = A[i]
            else:
                op = "down"
                prev = A[i]
        else:
            if op == "up":
                if prev <= A[i]:
                    prev = A[i]
                    continue
                else:
                    cnt += 1
                    op = None
                    prev = A[i]
            else:
                if prev >= A[i]:
                    prev = A[i]
                    continue
                else:
                    cnt += 1
                    op = None
                    prev = A[i]

    cnt += 1
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
N=int(sys.stdin.readline().strip())
A=map(int, sys.stdin.readline().split())
ans=0
trend=None
prev=None
for a in A:
    if prev is None:
        ans+=1
    elif prev<a:
        if trend is None:
            trend="plus"
        elif trend=="plus":
            pass
        elif trend=="minus":
            ans+=1
            trend=None
    elif prev>a:
        if trend is None:
            trend="minus"
        elif trend=="plus":
            ans+=1
            trend=None
        elif trend=="minus":
            pass
    elif prev==a:
        if trend is None:
            pass
        elif trend=="plus":
            pass
        elif trend=="minus":
            pass
    prev=a

print ans

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
N=int(sys.stdin.readline().strip())
A=map(int, sys.stdin.readline().split())
ans=0
trend=None
prev=None
for a in A:
    if prev is None:
        ans+=1
    elif prev<a:
        if trend is None:
            trend="plus"
        elif trend=="plus":
            pass
        elif trend=="minus":
            ans+=1
            trend=None
    elif prev>a:
        if trend is None:
            trend="minus"
        elif trend=="plus":
            ans+=1
            trend=None
        elif trend=="minus":
            pass
    elif prev==a:
        if trend is None:
            pass
        elif trend=="plus":
            pass
        elif trend=="minus":
            pass
    prev=a

print ans

Submission status: Accepted

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

flag = 0
ans = 1
cnt = 0
for i in range(n-1):
    if a[i+1] - a[i] > 0 and flag == -1 and cnt > 0:
        flag = 1
        ans += 1
        cnt = 0
    elif a[i+1] - a[i] < 0 and flag == 1 and cnt > 0: 
        flag = -1
        ans += 1
        cnt = 0
    elif a[i+1] - a[i] == 0:
        pass
    elif cnt == 0 and a[i+1] - a[i] > 0:
        flag = 1
        cnt += 1
    elif cnt == 0 and a[i+1] - a[i] < 0:
        flag = -1
        cnt += 1
print(ans)

Submission status: Accepted

Solution code:
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

n = ii()
A = iil()

cnt = 1
state = 'first'
for i in A:
#    print(i)
    if state == 'first':
        state = 'even'
    else:
        if state == 'even':
            if i > num:
                state = 'more'
            elif i < num:
                state = 'less'
        elif state == 'more':
            if i < num:
                cnt += 1
                state = 'even'
        elif state == 'less':
            if i > num:
                cnt += 1
                state = 'even'
    num = i
#print((cnt,state))
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

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

ans=0
up = 0

for i in range(n-1):
    if a[i] < a[i+1]:
        if up == -1:
            ans+=1
            up=0
        elif up==0:
            up=1
    elif a[i] > a[i+1]:
        if up == 1:
            ans+=1
            up=0
        elif up==0:
            up=-1

ans+=1
print(ans)

Submission status: Accepted

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

Ad = [A[i] - A[i+1] for i in range(N-1)]

ans = 1
p = 0
for d in Ad:
    if d * p < 0:
        ans += 1
        p = 0
    elif d != 0:
        p = d

print(ans)