Very simple java solution with O(n)


  • 0
    S
    public int[] maxSlidingWindow(int[] nums, int k) {
            if(nums.length==0){
    			int[] maxArray = {};
    			return maxArray;
            }
    		
    		int[] maxArray = new int[nums.length-k+1];
            
            int max=Integer.MIN_VALUE;
            int maxIndex=-1;
            for(int i=0,j=0,temp=0;i<nums.length;i++,temp++){
                if(nums[i]>=max){
                    max=nums[i];
                    maxIndex=i;
                }
                if(temp==k-1){
                	if((i-maxIndex)<k ){
                		maxArray[j++]=max;
                		temp--;
                	}else{
                		i=i-k;
                		temp=-1;
                		max=Integer.MIN_VALUE;
                        maxIndex=-1;
                	}
                }
            }
            return maxArray;
        }

Log in to reply
 

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