239. Sliding Window Maximum
https://www.youtube.com/watch?v=2SXqBsTR6a8
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
d = collections.deque()
out = []
for i, n in enumerate(nums):
while d and nums[d[-1]] < n:
d.pop()
d.append(i)
if d[0] == i - k: # 存了K+1個元素了
d.popleft()
if i >= k - 1:
out.append(nums[d[0]])
return out
907. Sum of Subarray Minimums
public int sumSubarrayMins(int[] A) {
Stack<Integer> s = new Stack<>();
int n = A.length, res = 0, mod = (int)1e9 + 7, j,k;
for (int i = 0; i <= n; i++) {
while (!s.isEmpty() && A[stack.peek()] > (i == n ? 0 : A[i])) {
j = stack.pop();
k = stack.isEmpty() ? -1 : stack.peek();
// i is right boundary k is left boundary
res = (res + A[j] * (i - j) * (j - k)) % mod;
}
stack.push(i);
}
return res;
}
class Solution:
def sumSubarrayMins(self, A):
res = 0
stack = [] # non-decreasing
A = [float('-inf')] + A + [float('-inf')]
for i, n in enumerate(A):
while stack and A[stack[-1]] > n:
cur = stack.pop()
res += A[cur] * (i - cur) * (cur - stack[-1])
stack.append(i)
return res % (10**9 + 7)