Java Solution runs O(kn) time O(1) space beats 98%


  • 0
    X
    public int[] maxSlidingWindow(int[] nums, int k) {
        int maxIndex=0;
        int currStorePtr=0;
        for(int i=0;i<nums.length;i++){
            if(i<=maxIndex+k-1){
                if(nums[i]>=nums[maxIndex]) {
                    maxIndex=i;
                }
            }
            else{
                maxIndex=i-k+1;
                for(int j=i-k+1;j<=i;j++){
                    if(nums[j]>=nums[maxIndex]) maxIndex=j;
                }
            }
            nums[currStorePtr]=nums[maxIndex];
    
            if(i>=k-1){
                currStorePtr++;
            }
        }
        return Arrays.copyOfRange(nums,0,currStorePtr);
    }

Log in to reply
 

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