0、贪心算法引入
详情请见:贪心算法
一、摇摆序列
1.1题目:
==========author daiV
一个整数序列,如果两个相邻元素的差正好正负交替出现,则称该序列为摇摆序列。
一个小于两个元素的序列直接为摇摆序列;
eg:{1,7,4,9,2,5},相邻元素的差为{6,-3,5,-7,3},该序列为摇摆序列
eg: {1,4,7,2,5},相邻元素的差为{3,3,-5,3};则不是摇摆序列
求:给定一个随机序列,求这个序列满足摇摆序列定义的最长序列的长度
如:输入{1,17,5,10,13,15,10,5,16,8}结果为7(1,17,5,15,5,16,8)
1.2思想实现
利用状态机思想来解决:
begin
up down
**1.3程序实现 **
#include<iostream>
#include<vector>
using namespace std;
class solution
{
public :
int wiggleMaxLength(std::vector<int> &nums)
{
if(nums.size()<2)
{
return nums.size();
}
static const int BEGIN = 0;
static const int UP = 1;
static const int DOWN = 2;
int STATE = BEGIN;
int max_length = 1;
for(int i = 1; i< nums.size();i++)
{
switch(STATE)
{
case BEGIN:
{
if(nums[i] > nums[i-1])
{
STATE = UP;
max_length++;
}
else if(nums[i]<nums[i-1])
{
STATE = DOWN;
max_length++;
}
}break;
case UP:if(nums[i] <nums[i-1])
{
STATE = DOWN;
max_length++;
}break;
case DOWN:if(nums[i] >nums[i-1])
{
STATE = UP;
max_length++;
}break;
}
}
return max_length;
}
};
int main()
{
std::vector<int> nums;
nums.push_back(1);
nums.push_back(17);
nums.push_back(5);
nums.push_back(10);
nums.push_back(13);
nums.push_back(15);
nums.push_back(10);
nums.push_back(5);
nums.push_back(16);
nums.push_back(8);
solution solve;
int max_length = solve.wiggleMaxLength(nums);
printf("该序列的最大子序列长度为:%d \n",max_length);
return 0;
}
**1.4程序结果 **