Straightforward Java one pass solution


  • 0
    H

    public class Solution {

    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 0) return new int[0];
        int[] res = new int[nums.length - k + 1];
        for (int i = 0; i <= nums.length - k; i++) {
            if (i > 0 && nums[i - 1] != res[i - 1]) {
                /*if the one we just passed is not the maximum for the past windows, we just need to compare the max of the past window and the new element  in the current window*/                                                     
                res[i] = Math.max(res[i - 1], nums[i + k - 1]);
                continue;
            }
            res[i] = maxSlidingWindow(nums, i, i + k);
        }
        return res;
    }
    
    private int maxSlidingWindow(int[] nums, int start, int end) {
        int max = nums[start];
        for (int i = start; i < end; i++) {
            max = Math.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.