- 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
- 58 lines of C++ from the credited upstream file 2519.cpp.
- 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: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 int kBigIndices(vector<int>& nums, int k) {32 const int n = nums.size();33 int ans = 0;34 FenwickTree leftTree(n);35 FenwickTree rightTree(n);36 37 vector<int> left(n);38 39 vector<int> right(n);40 41 for (int i = 0; i < n; ++i) {42 left[i] = leftTree.get(nums[i] - 1);43 leftTree.add(nums[i], 1);44 }45 46 for (int i = n - 1; i >= 0; --i) {47 right[i] = rightTree.get(nums[i] - 1);48 rightTree.add(nums[i], 1);49 }50 51 for (int i = 0; i < n; ++i)52 if (left[i] >= k && right[i] >= k)53 ++ans;54 55 return ans;56 }57};58