Problème
Slide a window of size k across the list one step at a time and report the maximum inside each window. A deque keeps this O(n).
Implement window_maximums(numbers, k).
Input
numbers: The list of integers. k: The window size.
Output
Return the maximum of each window, left to right.
Contraintes
1 ≤ k ≤ length ≤ 200,000
Exemples
Entrée :
numbers = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
Sortie attendue :
expected = [3, 3, 5, 5, 6, 7]
Entrée :
std::vector<long long> numbers = {1, 3, -1, -3, 5, 3, 6, 7};
long long k = 3;
Sortie attendue :
std::vector<long long> expected = {3, 3, 5, 5, 6, 7};
Entrée :
long[] numbers = new long[] {1, 3, -1, -3, 5, 3, 6, 7};
long k = 3;
Sortie attendue :
long[] expected = new long[] {3, 3, 5, 5, 6, 7};
Explication
Windows [1,3,-1], [3,-1,-3], [-1,-3,5], … have maxima 3, 3, 5, 5, 6, 7.
Entrée :
numbers = [4, 2]
k = 1
Sortie attendue :
expected = [4, 2]
Entrée :
std::vector<long long> numbers = {4, 2};
long long k = 1;
Sortie attendue :
std::vector<long long> expected = {4, 2};
Entrée :
long[] numbers = new long[] {4, 2};
long k = 1;
Sortie attendue :
long[] expected = new long[] {4, 2};
Explication
Windows of one element are the elements themselves: [4, 2].
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The maximum can disappear when it leaves the window, so you need a structure that updates by both value and index.
Indice 2
Keep candidate indices in decreasing order of their values, dropping anything outside the current window.
Indice 3
Watch the first full window and windows of size one; every answer must correspond to a fully formed window.
Complexité attendue
O(n) time, O(k) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.