bhupixb

Maximum in subarrat of size k

Jul 19th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <deque>
  3.  
  4. using namespace std;
  5.  
  6. // A Dequeue (Double ended queue) based method for printing maixmum element of
  7. // all subarrays of size k
  8. void printKMax(int arr[], int n, int k)
  9. {
  10. // Create a Double Ended Queue, Qi that will store indexes of array elements
  11. // The queue will store indexes of useful elements in every window and it will
  12. // maintain decreasing order of values from front to rear in Qi, i.e.,
  13. // arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
  14. std::deque<int> Qi(k);
  15.  
  16. /* Process first k (or first window) elements of array */
  17. int i;
  18. for (i = 0; i < k; ++i)
  19. {
  20. // For very element, the previous smaller elements are useless so
  21. // remove them from Qi
  22. while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
  23. Qi.pop_back(); // Remove from rear
  24.  
  25. // Add new element at rear of queue
  26. Qi.push_back(i);
  27. }
  28.  
  29. // Process rest of the elements, i.e., from arr[k] to arr[n-1]
  30. for ( ; i < n; ++i)
  31. {
  32. // The element at the front of the queue is the largest element of
  33. // previous window, so print it
  34. cout << arr[Qi.front()] << " ";
  35.  
  36. // Remove the elements which are out of this window
  37. while ( (!Qi.empty()) && Qi.front() <= i - k)
  38. Qi.pop_front(); // Remove from front of queue
  39.  
  40. // Remove all elements smaller than the currently
  41. // being added element (remove useless elements)
  42. while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
  43. Qi.pop_back();
  44.  
  45. // Add current element at the rear of Qi
  46. Qi.push_back(i);
  47. }
  48.  
  49. // Print the maximum element of last window
  50. cout << arr[Qi.front()];
  51. }
  52.  
  53. int main()
  54. {
  55. int arr[] = {12, 1, 78, 90, 57, 89, 56};
  56. int n = sizeof(arr)/sizeof(arr[0]);
  57. int k = 3;
  58. printKMax(arr, n, k);
  59. return 0;
  60. }
Add Comment
Please, Sign In to add comment