Java O(n) Solution


  • 0
    Y
    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            if(nums.length <= 0) return 0;
            int ans = 1, prev = nums[0], prevSign = 0;
            for(int idx = 1; idx < nums.length; idx++) {
                if(nums[idx] > prev) {
                    if(prevSign <= 0) ans++;
                    prevSign = 1;
                } else if(nums[idx] < prev) {
                    if(prevSign >= 0) ans++;
                    prevSign = -1;
                }
                prev = nums[idx];
            }
            return ans;
        }
    }
    

Log in to reply
 

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