How can I improve on this?


  • 0
    N

    While this solution passes all the test case, I'm not sure whether it's the most optimal one. Could someone suggest ways I could improve on this? Thank you so much!

    public class Solution {
        public int wiggleMaxLength(int[] nums) {
            if(nums.length <= 1) return nums.length;
            if(nums.length == 2 && nums[0] != nums[1]) return 2;
            if(nums.length == 2 && nums[0] == nums[1]) return 1;
            
            int[] memo = new int[nums.length];
            Arrays.fill(memo, 1);
            memo[nums.length-1] = 2;
            
            Boolean isPlus = false;
            
            for(int i = nums.length - 1; i > 0; i--) {
                int diff = nums[i] - nums[i-1];
                if(i == nums.length-1) {
                    if(diff < 0) isPlus = true;
                    else if(diff == 0) {
                        memo[i] = 1;
                        isPlus = null;
                    }
                } else {
                    if((diff > 0 && (isPlus == null || isPlus)) || (diff < 0 && (isPlus == null || !isPlus))) {
                        memo[i] = memo[i+1] + 1;
                        isPlus = diff < 0 ? true : false;
                    } else {
                        memo[i] = memo[i+1];
                    }
                }
                //for(int num : memo) System.out.print(num + " ");
                //System.out.println();
            }
            return memo[1] == 0 ? 1 : memo[1];
        }
    }
    

Log in to reply
 

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