Skip to content

Instantly share code, notes, and snippets.

@djade007
Created April 15, 2021 05:37
Show Gist options
  • Save djade007/b1c28d3a170437b60caa2a56cfa75a0e to your computer and use it in GitHub Desktop.
Save djade007/b1c28d3a170437b60caa2a56cfa75a0e to your computer and use it in GitHub Desktop.
temperature
// All the methods run in O(1) time and O(1) space
class TempTracker {
constructor() {
this.max = -Infinity;
this.min = Infinity;
this.avg = 0;
// Keep the total insert count to be able to compute the previous sum from the average
this.tempCount = 0;
}
insert(value) {
this.max = Math.max(this.max, value);
this.min = Math.min(this.min, value);
const previousSum = this.avg * this.tempCount;
this.avg = (previousSum + value) / ++this.tempCount;
}
getHighest() {
return this.max;
}
getLowest() {
return this.min;
}
getAverage() {
return this.avg;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment