1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <bits/stdc++.h>
using namespace std;
enum { ASCENDING, DESCENDING };
enum { LOWEST, UNCHANGED, HIGHEST };

int a[50005];
int dp[50005][2][3];
int32_t main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;

    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }

    dp[1][ASCENDING][LOWEST] = dp[1][ASCENDING][HIGHEST] = 1;
    dp[1][DESCENDING][LOWEST] = dp[1][DESCENDING][HIGHEST] = 1;
    for (int i = 2; i <= n; i++) {
        // Ascending.
        dp[i][ASCENDING][LOWEST] = 1e9;

        dp[i][ASCENDING][UNCHANGED] =
            min(dp[i - 1][DESCENDING][LOWEST],
                ((a[i - 1] < a[i]) ? dp[i - 1][DESCENDING][UNCHANGED] : 1000000));

        dp[i][ASCENDING][HIGHEST] =
            min(dp[i - 1][DESCENDING][LOWEST] + 1, dp[i - 1][DESCENDING][UNCHANGED] + 1);
        // Descending.
        dp[i][DESCENDING][LOWEST] =
            min(dp[i - 1][ASCENDING][HIGHEST] + 1, dp[i - 1][ASCENDING][UNCHANGED] + 1);
        dp[i][DESCENDING][UNCHANGED] =
            min(dp[i - 1][ASCENDING][HIGHEST],
                ((a[i - 1] > a[i]) ? dp[i - 1][ASCENDING][UNCHANGED] : 1000000));

        dp[i][DESCENDING][HIGHEST] = 1e9;
    }

    cout << min({dp[n][0][0], dp[n][0][1], dp[n][0][2], dp[n][1][0], dp[n][1][1], dp[n][1][2]})
         << "\n";
}