spoj ARRAYSUB: O(n) Complexity Approach

前端 未结 2 1978
温柔的废话
温柔的废话 2021-01-05 12:44

I was trying to solve this problems on spoj http://spoj.pl/problems/ARRAYSUB

I solved it using two approaches

firstly using optimised brute force. Secondly

2条回答
  •  遥遥无期
    2021-01-05 13:18

    The data structure to be used to solve this problem in O(n) time is "deque"

    A natural way most people would think is to try to maintain the queue size the same as the window’s size. Try to break away from this thought and try to think outside of the box. Removing redundant elements and storing only elements that need to be considered in the queue is the key to achieve the efficient O(n) solution below.

      void maxInWindow(vector &A, int n, int k, vector &B) {
      deque Q;
      for (int i = 0; i < k; i++) {
        while (!Q.empty() && A[i] >= A[Q.back()])
          Q.pop_back();
        Q.push_back(i);
      }
      for (int i = k; i < n; i++) {
        B[i-k] = A[Q.front()];
        while (!Q.empty() && A[i] >= A[Q.back()])
          Q.pop_back();
        while (!Q.empty() && Q.front() <= i-k)
          Q.pop_front();
        Q.push_back(i);
      }
      B[n-k] = A[Q.front()];
      //B stores the maximum of every contiguous sub-array of size k    
    }
    

    Explanation :

    The first for loop calculates the maximum of the first 'k' elements and store the index at Q.front(). This becomes B[0] = A[index]. The next section, we push and pop from the back if A[i] is greater than the previous maximum stored. We pop from front if the value of the index is less than i-k which means it is no more relevant.

提交回复
热议问题