- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 81 lines of C++ from the credited upstream file 3187.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree {2 public:3 FenwickTree(int n) : sums(n + 1) {}4 5 void add(int i, int delta) {6 while (i < sums.size()) {7 sums[i] += delta;8 i += lowbit(i);9 }10 }11 12 int get(int i) const {13 int sum = 0;14 while (i > 0) {15 sum += sums[i];16 i -= lowbit(i);17 }18 return sum;19 }20 21 private:22 vector<int> sums;23 24 static inline int lowbit(int i) {25 return i & -i;26 }27};28 29class Solution {30 public:31 vector<int> countOfPeaks(vector<int>& nums, vector<vector<int>>& queries) {32 vector<int> ans;33 vector<int> peak = getPeak(nums);34 FenwickTree tree(peak.size());35 36 for (int i = 0; i < peak.size(); ++i)37 tree.add(i + 1, peak[i]);38 39 40 41 auto update = [&](int i) {42 const int newPeak = isPeak(nums, i);43 if (newPeak != peak[i]) {44 tree.add(i + 1, newPeak - peak[i]);45 peak[i] = newPeak;46 }47 };48 49 for (const vector<int>& query : queries)50 if (query[0] == 1) {51 const int l = query[1];52 const int r = query[2];53 ans.push_back(r - l < 2 ? 0 : tree.get(r) - tree.get(l + 1));54 } else if (query[0] == 2) {55 const int index = query[1];56 const int val = query[2];57 nums[index] = val;58 update(index);59 if (index > 0)60 update(index - 1);61 if (index + 1 < nums.size())62 update(index + 1);63 }64 65 return ans;66 }67 68 private:69 vector<int> getPeak(const vector<int>& nums) {70 vector<int> peak(nums.size());71 for (int i = 1; i + 1 < nums.size(); ++i)72 peak[i] = nums[i] > nums[i - 1] && nums[i] > nums[i + 1];73 return peak;74 }75 76 bool isPeak(const vector<int>& nums, int i) {77 return i > 0 && i + 1 < nums.size() && nums[i] > nums[i - 1] &&78 nums[i] > nums[i + 1];79 }80};81