Sliding Window Maximum
LeetCode 239 · कठीण · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Monotonic decreasing deque; front = window max.
मी Sliding Window Maximum (LeetCode 239) असा सोडवला — Monotonic Queue पॅटर्नमधील एक कठीण प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
Approach
- 1
Pop expired indices from the front.
- 2
Pop indices with smaller or equal values from the back.
- 3
Append the current index.
- 4
Once the first window is full, record nums[dq[0]].
मी कसा सोडवला
Monotonic dequePythonO(n) time · O(k) space
class Solution:
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
#monotonic deque
"""
nums = [1,3,-1,-3,5,3,6,7], k = 3
monotonically decreasing deque
front back
a) Remove indices from front if these are expired or outside the current window
b) Remove indices from back if their corresponding values are smaller or eqaul to the current element
c) front = always contains the candidate maximum
d) back = candidate may be removed because a larger element arrivec
"""
result=[]
dq = deque([])
n = len(nums)
for i in range(n):
#expired/out of window items remove from front
while dq and dq[0]<=i-k:
dq.popleft()
#Remove indices from back if their corresponding values are smaller or eqaul to the current element
while dq and nums[dq[-1]]<=nums[i]:
dq.pop()
dq.append(i)
#window is complete
if i>=k-1:
#keep the candidate maximum
result.append(nums[dq[0]])
return resultSliding Window Maximum — वारंवार विचारले जाणारे प्रश्न
Sliding Window Maximum मागील intuition काय आहे?
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
Sliding Window Maximum (LeetCode 239) कसा सोडवावा?
1. Pop expired indices from the front. 2. Pop indices with smaller or equal values from the back. 3. Append the current index. 4. Once the first window is full, record nums[dq[0]].
Sliding Window Maximum ची time आणि space complexity किती आहे?
Time: O(n). Space: O(k). (Accepted approach: Monotonic deque.)
Sliding Window Maximum मध्ये सामान्य चुका कोणत्या?
Store indices, not values — you need them to expire elements.