From 1cdf88bea80296930efa94764a33417f77b29f25 Mon Sep 17 00:00:00 2001 From: Luca Lombardo Date: Sat, 30 Sep 2023 19:55:46 +0200 Subject: [PATCH] readme fixed --- 2023_09_21/README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 2023_09_21/README.md diff --git a/2023_09_21/README.md b/2023_09_21/README.md new file mode 100644 index 0000000..ef51426 --- /dev/null +++ b/2023_09_21/README.md @@ -0,0 +1,48 @@ +> Problem: [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) + +# Comments on the solution + +The problem is to find the maximum value in a sliding window of size `k` over a given array of integers. We can solve this problem using a double-ended queue (deque) to store the indices of the elements in the sliding window. The deque will always store the indices of the elements in decreasing order of their values, with the maximum value at the front of the deque. + +We start by initializing an empty deque and two pointers `l` and `r` to the left and right ends of the sliding window. We then iterate over the elements of the array, adding each element to the deque and removing the smaller elements from the back of the deque. We also remove the leftmost element from the deque if it's out of the window. Finally, we append the maximum value to the output if the window size is `k`. + + +### Complexity analysis + +* **Time complexity**: `O(n)`, where `n` is the length of the input array. This is because each element is added to and removed from the deque at most once, and each element is processed by the while loop at most once. + +* **Space complexity**: `O(k)`, where `k` is the size of the sliding window, as the deque can store at most `k` elements at any time. + +--- + +### Rust solution + +```rust +fn max_sliding_window(nums: Vec, k: i32) -> Vec { + let mut output = Vec::new(); + let mut q: VecDeque = VecDeque::new(); + let (mut l, mut r) = (0, 0); + + while r < nums.len() { + while !q.is_empty() && nums[*q.back().unwrap()] < nums[r] { + q.pop_back(); + } + q.push_back(r); + + if l > q[0] { + q.pop_front(); + } + + if (r + 1) as usize >= k as usize { + output.push(nums[*q.front().unwrap()]); + l += 1; + } + r += 1; + } + output +} +``` + +### Leetcode result + +![](https://i.imgur.com/OR15Xve.png)