- analysis
This question is a greedy question. If the points in the array are drawn in two-dimensional coordinates, it is a polyline. You only need to count the number of inflection points.
It should be noted that the code uses the idea of automata, which is more readable than the code that only writes if else
If you write such code in an interview, you can show a solid basic skill.
- Code
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int size = nums.size();
if(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 < 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 - 1] > nums[i]){
state = DOWN;
++max_length;
}
break;
case DOWN:
if(nums[i - 1] < nums[i]){
state = UP;
++max_length;
}
break;
}
}
return max_length;
}
};