func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
var res: [Int] = []
guard nums.isEmpty == false else {
return res
}
var left = 0, right = k - 1
/// 存放每个段落的最大值下标,Key为右边界
var dp: [Int : Int] = [:]
while right < nums.count {
let newItem = nums[right]
if let lastmaxIdx = dp[right - 1], lastmaxIdx >= left {// 上一个最大值在当前范围内
let lastMax = nums[lastmaxIdx]
if lastMax > newItem {
res.append(lastMax)
dp[right] = lastmaxIdx
}
else {
res.append(newItem)
dp[right] = right
}
}
else {
var curMaxIdx = right
var curMax = nums[curMaxIdx]
for i in left..<right {
if nums[i] > curMax {
curMaxIdx = i
curMax = nums[curMaxIdx]
}
}
res.append(curMax)
dp[right] = curMaxIdx
}
right += 1
left += 1
}
return res
}