2

I am trying to keep track of a rolling min/max within a fixed size container (deque in my case).

I have a struct like this

struct {
    double min;
    double max;
    std::deque<double> queue;
}

currently my code is like this

void onNewElement(double new) {
  if (queue not full) {
    if (new < min) {
       min = new;
    }
    if (new > max) {
       max = new;
    }

    queue.push_back(new);
  } else {
    auto front = queue.front();
    queue.pop_front();

    queue.push_back(new);
    
    // TODO: Improve this logic
    if (min == front || max == front) {
      updateNewMinMax();
    }
  }

  void updateNewMinMax() {
    // this method just loops through all elements in queue and find the min max, then set member 
    // variables
  }

i somehow think there must be a more heuristic way when updating the queue (the TODO). For example, when I pop the front of the queue, maybe if the front is the min or max, and after popping, the front is of same value as the popped front, the update method can be skipped.

There should also be some logic to check on the new value before pushing into the queue, like if value to be pushed is less than min, it would by definition be the new Min, etc.

I think my current solution is similar to what i saw from this post Get Min/Max in O(1) time from a Queue?

Would appreciate if someone could point a simplified logic for this

edwardlam0328
  • 315
  • 1
  • 7

0 Answers0