- 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
- 79 lines of Java from the credited upstream file 3187.java.
- 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 FenwickTree(int n) {3 sums = new int[n + 1];4 }5 6 public void add(int i, int delta) {7 while (i < sums.length) {8 sums[i] += delta;9 i += lowbit(i);10 }11 }12 13 public int get(int i) {14 int sum = 0;15 while (i > 0) {16 sum += sums[i];17 i -= lowbit(i);18 }19 return sum;20 }21 22 private int[] sums;23 24 private static int lowbit(int i) {25 return i & -i;26 }27}28 29class Solution {30 public List<Integer> countOfPeaks(int[] nums, int[][] queries) {31 List<Integer> ans = new ArrayList<>();32 int[] peak = getPeak(nums);33 FenwickTree tree = new FenwickTree(peak.length);34 35 for (int i = 0; i < peak.length; ++i)36 tree.add(i + 1, peak[i]);37 38 39 40 for (int[] query : queries) {41 if (query[0] == 1) {42 final int l = query[1];43 final int r = query[2];44 ans.add(r - l < 2 ? 0 : tree.get(r) - tree.get(l + 1));45 } else if (query[0] == 2) {46 final int index = query[1];47 final int val = query[2];48 nums[index] = val;49 update(nums, peak, tree, index);50 if (index > 0)51 update(nums, peak, tree, index - 1);52 if (index + 1 < nums.length)53 update(nums, peak, tree, index + 1);54 }55 }56 57 return ans;58 }59 60 private void update(int[] nums, int[] peak, FenwickTree tree, int i) {61 final int newPeak = isPeak(nums, i) ? 1 : 0;62 if (newPeak != peak[i]) {63 tree.add(i + 1, newPeak - peak[i]);64 peak[i] = newPeak;65 }66 }67 68 private int[] getPeak(int[] nums) {69 int[] peak = new int[nums.length];70 for (int i = 1; i + 1 < nums.length; i++)71 peak[i] = nums[i] > nums[i - 1] && nums[i] > nums[i + 1] ? 1 : 0;72 return peak;73 }74 75 private boolean isPeak(int[] nums, int i) {76 return i > 0 && i + 1 < nums.length && nums[i] > nums[i - 1] && nums[i] > nums[i + 1];77 }78}79