Description
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?
Input
Input is given from Standard Input in the following format:
N
A1 A2 … AN
Output
Print the minimum possible number of subarrays after division of A.
Sample Input
6
1 2 3 2 2 1
Sample Output
2
One optimal solution is to divide the array into [1,2,3] and [2,2,1].
Hint
1≤N≤105
1≤Ai≤109
Each Ai is an integer.
题意
找出一个数组内 非递减数列,非递增数列 一个有几个;
题解:
明显的贪心思想
蒟蒻在多开个数组进行标记
AC代码
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
int n, arr[N], dp[N];
int main()
{
int n;
scanf("%d",&n);
for(int i = 0;i < n; i++)
cin>>arr[i];
int ans, res;
for(int i = 0;i < n; i++) {
dp[i+1] = INF;
if(i>=1 && arr[i-1]>arr[i]) ans = i;
else dp[i+1] = dp[ans]+1;
if(i>=1 && arr[i-1]<arr[i]) res = i;
else dp[i+1] = min(dp[i+1],dp[res]+1);
}
cout<<dp[n]<<endl;
return 0;
}