My concise python solution beat 98% submissions with comments


  • 0
    K
    def maxSlidingWindow(self, nums, k):
        # k is always valid given.
        if not nums:
            return []
        res = [max(nums[0:k])]
        for i in range(k,len(nums)):
            # if new num is max
            if nums[i] >= res[i-k]:
                res.append(nums[i])
            # if max is num[i-k] which has been moved out, find new max, else keep old max
            elif nums[i-k] == res[i-k]:
                res.append(max(nums[i-k+1:i+1]))
            else:
                res.append(res[i-k])
        return res

  • 0
    K

    The worst time complexity can be O(kn), but on average it is O(n).


Log in to reply
 

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