My Java Solution


  • 0
    F

    I came up with following O(n) solution :

    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            int len = 0;
            int positive = 0;
            int negative = 0;
            if(nums.length == 0)
                return 0;
            if(nums.length == 1)
                return 1;
            if(nums[1]-nums[0] > 0){
                negative = 0;
                positive = 1;
                len = 1;
            }else if(nums[1]-nums[0] < 0){
                positive = 0;
                negative = 1;
                len += 1;
            }else{
                negative = 1;
                positive = 1;
            }
            for(int i=2;i<nums.length;i++){
                if(nums[i]-nums[i-1] > 0 && negative == 1){
                    negative = 0;
                    positive = 1;
                    len += 1;
                }else if(nums[i]-nums[i-1] < 0 && positive == 1){
                    positive = 0;
                    negative = 1;
                    len += 1;
                }else{
                    if(nums[i] == nums[i-1])
                        continue;
                }
            }
            return len+1;
        }
    }
    
    
    

Log in to reply
 

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