H - Sorted Arrays AtCoder - 2367

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

题意:判断非递减数列,非递增数列的和;

思路:循环跑一遍O(n),res标记是否确定flag的真假,flag标记非递增还是非递减;

#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long LL;
using namespace std;
#define max_n 100005

int a[max_n];

int main()
{
	int n,k=1,ans,i;
	bool flag,res=false;
	scanf("%d",&n);
	scanf("%d",&a[0]);
	if(n==1)
	{
		printf("1\n");
		return 0;
	}
	ans=a[0];
	for(i=1;i<n;i++)
	{
		scanf("%d",&a[i]);
		if(!res)
		{
			if(a[i]>ans)
			{
				flag=true;
				res=true;
				ans=a[i];
			}
			else if(a[i]<ans)
			{
				flag=false;
				res=true;
				ans=a[i];
			}
		}
		else
		{
			if(flag)
			{
				if(a[i]>=ans)
					ans=a[i];
				else
				{
					k++;
					ans=a[i];
					res=false;
				}
			}
			else
			{
				if(a[i]<=ans)
					ans=a[i];
				else
				{
					k++;
					ans=a[i];
					res=false;
				}
			}
		}
	}
	printf("%d\n",k);
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值