classSolution { publicintwiggleMaxLength(int[] nums) { // corner case, as described, if there are only 1 element return 1 // if there are two elements and they are not equal, return 2 if (nums.length == 1) { return1; }elseif (nums.length == 2) { if (nums[0] != nums[1]) { return2; } return1; }
// result is initialized as 1, as the rightest one is always regarded as a waggle intresult=1;
// intprevDiff=0; intcurDiff=0;
for (inti=0; i < nums.length - 1; i++) { curDiff = nums[i + 1] - nums[i]; if (prevDiff >= 0 && curDiff < 0 || prevDiff <=0 && curDiff > 0) { result++; // update prevDiff only when a waggle is found, and recordsits direction prevDiff = curDiff; } }