Easy Java solution. Stack. O(N)


  • 0
    H
    class Solution {
        public int wiggleMaxLength(int[] nums) {
            Stack<Integer> stack = new Stack<>();
            
            int next = 0;
            
            for(int i : nums){
                if(stack.isEmpty()){
                    stack.push(i);
                }
                else if(stack.size() == 1){
                    if(i > stack.peek()){
                        stack.push(i);
                        next = -1;
                    }
                    else if(i < stack.peek()){
                        stack.push(i);
                        next = 1;
                    }
                }
                else if(i > stack.peek()){
                    if(next == -1) {
                        stack.pop();
                        stack.push(i);
                    }
                    else if(next == 1){
                        stack.push(i);
                        next = -1;
                    }
                }
                else if(i < stack.peek()){
                    if(next == 1) {
                        stack.pop();
                        stack.push(i);
                    }
                    else if(next == -1){
                        stack.push(i);
                        next = 1;
                    }
                }
            }
            
            return stack.size();
            
        }
    }
    

Log in to reply
 

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