Java Simple solution - no DP required


  • 0
    D
    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            int n = nums.length;
            if (n == 0)
                return 0;
            else if (n == 1)
                return 1;
            int len = 1;
            int comp = 0; // 1: increasing, 0: equal, -1: decreasing
            for (int i = 1; i < n; i++) {
                if (nums[i] > nums[i-1]) {
                    if (comp == -1 || comp == 0)
                        len++;
                    comp = 1;
                } else if (nums[i] < nums[i-1]) {
                    if (comp == 1 || comp == 0)
                        len++;
                    comp = -1;
                }
            }
            return len;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.