Back to course home
0% completed
Vote For New Content
Problem 6: Max of All Subarrays of Size 'k'
Kartheek Penagamuri
Jan 6, 2024
The following solution also passed all the test cases. When compared to the solution provided by the author, the only difference is that I used if block to remove out of range elements from the dequeue instead of a while loop. I am having hard time to come up with a test case where my code fails but the solution that has while loop to remove out of range elements from the dequeue succeeds.
public class Solution {
public List<int> printMax(int[] arr, int k) {
List<int> result = new List<int>();
// ToDo: Write Your Code Here.
LinkedList<int> dequeue = new LinkedList<int>();
for (int i = 0; i < arr.Length; i++)
{
if (dequeue.Count > 0 && dequeue.First.Value < i - k + 1)
dequeue.RemoveFirst();
while (dequeue.Count > 0 && arr[dequeue.Last.Value] <= arr[i])
dequeue.RemoveLast();
dequeue.AddLast(i);
if (i >= k - 1)
result.Add(arr[dequeue.First.Value]);
}
return result;
}
}
0
0
Comments
Comments
On this page