- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 57 lines of C++ from the credited upstream file 1093.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<double> sampleStats(vector<int>& count) {4 const int n = accumulate(count.begin(), count.end(), 0);5 const double mode = ranges::max_element(count) - count.begin();6 return {7 getMinimum(count),8 getMaximum(count),9 getMean(count, n),10 (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0,11 mode,12 };13 }14 15 private:16 double getMinimum(const vector<int>& count) {17 for (int i = 0; i < count.size(); ++i)18 if (count[i])19 return i;20 return -1;21 }22 23 double getMaximum(const vector<int>& count) {24 for (int i = count.size() - 1; i >= 0; --i)25 if (count[i])26 return i;27 return -1;28 }29 30 double getMean(const vector<int>& count, double n) {31 double mean = 0;32 for (long i = 0; i < count.size(); ++i)33 mean += (i * count[i]) / n;34 return mean;35 }36 37 double getLeftMedian(const vector<int>& count, double n) {38 int numCount = 0;39 for (int i = 0; i < count.size(); ++i) {40 numCount += count[i];41 if (numCount >= n / 2)42 return i;43 }44 return -1;45 }46 47 double getRightMedian(const vector<int>& count, double n) {48 int numCount = 0;49 for (int i = count.size() - 1; i >= 0; --i) {50 numCount += count[i];51 if (numCount >= n / 2)52 return i;53 }54 return -1;55 }56};57