Accepted C# Solution


  • 2
    M
    public int[] MaxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.Length == 0) return new int[0];
            if(nums.Length < k) return new int[1]{nums.Max()};
            var result = new int[nums.Length - k + 1];
            var d = new LinkedList<int>();
    
            for (var i = 0; i < nums.Length; i++)
            {
                if(d.Any() && d.First() == i-k) d.RemoveFirst();
    
                //Remove the item that less than nums[i], since they are useless
                while(d.Any() && nums[d.Last()] < nums[i]) d.RemoveLast();
                d.AddLast(i);
    
                if (i >= k-1)
                {
                    result[i - k + 1] = nums[d.First()];
                }
            }
            return result;
    }

Log in to reply
 

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