求一个序列的最大连续长度

来源:互联网 发布:鸟哥linux基础篇 视频 编辑:程序博客网 时间:2024/05/21 11:06

题目要求:
给定一个递增序列,求该序列的连续最大长度。
解题思路:依次遍历,当序列数字连续时,增加其长度,当不连续时,重新初始化长度,最终返回该序列的最大连续长度。

#include<iostream>using namespace std;int getMaxSize(int* array,int length){    int count = 1;    int num = 0;    for(int i = 0;i<length;i++)    {        if(array[i+1]==array[i]+1)        {           ++count;        }         else        {            count = 1;   //重新初始化长度,继续遍历            continue;        }        if(num<count)        {           num = count;  //保证最终返回的长度是序列中最大连续长度        }    }    return num;}int main(){    int str[13] = {1,2,3,4,5,3,1,2,3,4,5,6,8};    int num = getMaxSize(str,13);    cout<<num<<endl;}