Simple Java Solution DP O(n) time complexity, O(1) space complexity


  • 1
    J
    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            if (nums.length <= 1) return nums.length;
            int pre_sign = 0;
            int signLen = 0;  
            for (int i = 1; i < nums.length; i++) {
                int sign = nums[i] - nums[i-1];
                if (sign == 0 || sign * pre_sign > 0) continue;
                else {
                    signLen++;
                    pre_sign = sign; 
                }
            }
            return ++signLen;
        }
    }
    

Log in to reply
 

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