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

Solution in Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)


import java.util.*;
import java.io.*;
public class Main
{
    static int[] ar;
    static int[][] dp;
    public static void main(String[] args) throws Exception{
        BufferedReader bff=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wff=new PrintWriter(System.out);
        bff.readLine();
        String[] st=bff.readLine().split(" ");
        ar=new int[st.length];
        for(int i=0;i<st.length;i++){
            int k=Integer.parseInt(st[i]);
            ar[i]=k;
        }
        dp=new int[ar.length][2];
        for(int[] aux:dp){
            Arrays.fill(aux,-1);
        }
        int res=Math.min(calcular(ar[0],1,0),calcular(ar[0],1,1));
        wff.println(res);
        wff.flush();
    }

    public static int calcular(int k,int i,int way){
        int res=1;
        if(i<ar.length){
            if(way==-1){
                int aux=ar[i];
                if(aux!=k){
                    if(k-aux>0){
                        res=calcular(aux,i+1,0);
                    }
                    else{
                        res=calcular(aux,i+1,1);
                    }
                }
                else{
                    res=calcular(k,i+1,way);
                }
            }
            else{
                if(dp[i][way]==-1){
                    int aux=ar[i];
                    if(way==0){
                        if(k-aux>=0){
                            res=Math.min(1+calcular(aux,i+1,-1),calcular(aux,i+1,way));
                        }
                        else{
                            res=1+calcular(aux,i+1,-1);
                        }
                    }
                    else{
                        if(k-aux<=0){
                            res=Math.min(1+calcular(aux,i+1,-1),calcular(aux,i+1,way));
                        }
                        else{
                            res=1+calcular(aux,i+1,-1);
                        }
                    }
                    dp[i][way]=res;
                }
                else{
                    res=dp[i][way];
                }
            }
        }
        return res;
    }
}