C# solution


  • 0
    K

    1.Check array length & distinct count
    2.Compare in foreach

        public int WiggleMaxLength(int[] nums) {
                if(nums.Length < 3 ||nums.Distinct().Count()<2) return nums.Distinct().Count();
                int cursor=nums[0]==nums[1]?1:0;
                int current = nums[cursor+1];
                int dir = nums[cursor] < current ? 1 : -1;
                int wiggle = 2;
                for(int i = cursor+2; i < nums.Length; i++)
                {
                    int next = nums[i];
                    
                    if ((current - next) * dir > 0)
                    {
                            wiggle++;
                            current = next;
                            dir *= -1;
                    }
                    else 
                    {
                            current = next;
                    }
                }
                return wiggle;
        }
    }

Log in to reply
 

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