Simple Java Solution


  • 0

    Greedy algorithm is enough for this problem.

        public int wiggleMaxLength(int[] nums) {
            if (nums.length == 0) return 0;
            
            // Expectation: positive: expecting a larger number
            //              negative: expecting a smaller number
            //              0       : whatever (just for the first iteration)
            int expectation = 0, len = 1;
            
            for (int i = 1; i < nums.length; ++i) {
                if (nums[i] < nums[i-1] && expectation <= 0) {
                    expectation = 1; // flip
                    len++;
                } else if (nums[i] > nums[i-1] && expectation >= 0) {
                    expectation = -1; // flip
                    len++;
                }
            }
            
            return len;
        }
    

Log in to reply
 

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