Created
April 15, 2021 05:37
-
-
Save djade007/b1c28d3a170437b60caa2a56cfa75a0e to your computer and use it in GitHub Desktop.
temperature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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