- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 57 lines of Java from the credited upstream file 2519.java.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure 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 int kBigIndices(int[] nums, int k) {31 final int n = nums.length;32 int ans = 0;33 FenwickTree leftTree = new FenwickTree(n);34 FenwickTree rightTree = new FenwickTree(n);35 36 int[] left = new int[n];37 38 int[] right = new int[n];39 40 for (int i = 0; i < n; ++i) {41 left[i] = leftTree.get(nums[i] - 1);42 leftTree.add(nums[i], 1);43 }44 45 for (int i = n - 1; i >= 0; --i) {46 right[i] = rightTree.get(nums[i] - 1);47 rightTree.add(nums[i], 1);48 }49 50 for (int i = 0; i < n; ++i)51 if (left[i] >= k && right[i] >= k)52 ++ans;53 54 return ans;55 }56}57