- 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
- 52 lines of Java from the credited upstream file 2031.java.
- The implementation visibly relies on sequence storage.
- 3 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 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 subarraysWithMoreZerosThanOnes(int[] nums) {31 final int MOD = 1_000_000_007;32 final int n = nums.length;33 int ans = 0;34 int prefix = 0;35 FenwickTree tree = new FenwickTree(2 * n + 1);36 tree.add(remap(0, n), 1);37 38 for (final int num : nums) {39 prefix += num == 0 ? -1 : 1;40 ans += tree.get(remap(prefix - 1, n));41 ans %= MOD;42 tree.add(remap(prefix, n), 1);43 }44 45 return ans;46 }47 48 private int remap(int i, int n) {49 return i + n + 1;50 }51}52