Very Simple Java Solution using only boolean values, No DP(with comments)


  • 0
    S

    Boolean value initialization is needed only for the first and second value, rest is taken care by the loop and the if else conditions.

    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            int a = nums.length ;
            if(a < 2){
                return a;
            }
            
            int count = 1;
            
            boolean nextIsBig = false;
            boolean nextIsSmall = false;
            
            if(nums[1] > nums[0]){
                nextIsSmall = true;
                count++;
            }
            else if(nums[1] < nums[0]){
                nextIsBig = true;
                count++;
            }
            else{
                // For the case if the first two elements are equal
                nextIsBig = true;
                nextIsSmall = true;
            }
            
            
            for(int i=2;i<a;i++){
                if(nextIsSmall == true && nums[i] < nums[i-1]){
                    count++;
                    nextIsBig = true;
                    nextIsSmall = false;
                }
                else if(nextIsBig == true && nums[i] > nums[i-1]){
                    count++;
                    nextIsSmall= true;
                    nextIsBig = false;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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