simple java solution O(n) with explanation


  • 0
    J
    public class Solution {
        public int wiggleMaxLength(int[] nums) {
    		   int len=0;
    		   int last=-1;
    		   int seclast=-1;
    	      for(int index=0;index<nums.length;index++){
    	    	   if(last==nums[index]) continue;//if current value is equal to the last number
    		       if(len>=2 && !((nums[index]-last)*(last-seclast)<0)){//if the current number is not suitable to be include in this sequance
    		          last=last-seclast>0?Math.max(last, nums[index]):Math.min(last, nums[index]);
    		          continue;
    		        }
    		        seclast=last;
    		        last=nums[index];
    		        len++;	        	
    	       }
    	      return len;
    	 }
    }
    

Log in to reply
 

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