Java Solution


  • 0
    V

    I am trying to re-use the work that is already done I mean

    1. First find maximum number from first k numbers from array so in example
      1,3,-1 were first k numbers in array so we fetch maximum from it
      which will be 3 in this case so set 3 on 0th index of result
    public int getMax(int nums[]) 
    {
        int max = nums[0];
        for (int i = 0; i < nums.length; i++) 
        {
            if (nums[i] >= max) {
    	    max = nums[i];
            }
        }
        return max;
    } 
    
    1. Iterate from k th element to n th element in array and
    for (int i = k; i < nums.length; i++)		
    
    1. Recalculate maximum for (i - k) + 1 element to i+1 element only if the number which was left out from window in last iteration was maximum number
    if (nums[i - k] == max) {
        max = getMax(Arrays.copyOfRange(nums, (i - k) + 1, i + 1));
        result[index] = max;
    }
    

    else calculate newly introduced number with previous maximum number and set result accordingly

    else                                                          
    {
        if (result[index - 1] < nums[i])
            result[index] = nums[i];
        else
    	result[index] = result[index - 1];   
    }
    

    code :

    public int[] maxSlidingWindow(int[] nums, int k) 
    {                                                                                                                 
        if (nums.length <= 0)
            return nums;
        int result[] = new int[(nums.length - k) + 1];
        int index = 0;
        int max = getMax(Arrays.copyOfRange(nums, 0, k));
        result[index] = max;
        for (int i = k; i < nums.length; i++) {
            index++;
    	if (nums[i - k] == max) {
    	    max = getMax(Arrays.copyOfRange(nums, (i - k) + 1, i + 1));
    	    result[index] = max;
    	} else {
    	    if (result[index - 1] < nums[i])
    	        result[index] = nums[i];
    	    else
    		result[index] = result[index - 1];
    	}
        }
        return result;
    }
    
    public int getMax(int nums[]) {
        int max = nums[0];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= max) {
    	    max = nums[i];
    	}
        }
        return max;
    }
    
    

Log in to reply
 

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