Straight forward Java solution not using deque


  • 0
    C
        public int[] maxSlidingWindow(int[] nums, int k) {
            int n=nums.length;
            int[] res=new int[n-k+1];
            if(nums==null||nums.length==0) return nums;
            int max=nums[0];
            int maxindex=0;
            for(int i=1;i<k;i++){
                if(nums[i]>=max){
                    maxindex=i;
                    max=nums[i];
                }
            }
            res[0]=max;
            int p=1;
            for(int j=k;j<nums.length;j++){
                if(nums[j]>=max){
                    maxindex=j;
                    max=nums[j];
                    res[p++]=max;
                }
                else{
                    if(maxindex==j-k){
                        max=nums[j-k+1];
                        maxindex=j-k+1;
            for(int i=j-k+2;i<j+1;i++){
                if(nums[i]>=max){
                    maxindex=i;
                    max=nums[i];
                }
            }
            res[p++]=max;
                    }
                    else{
                        res[p++]=max;
                    }
                }
            }
            return res;
        }

Log in to reply
 

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