|
| 1 | +/** |
| 2 | + * Title: Count of Range Sum |
| 3 | + * Description: Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 10/04/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number[]} nums |
| 10 | + * @param {number} lower |
| 11 | + * @param {number} upper |
| 12 | + * @return {number} |
| 13 | + */ |
| 14 | +function SegmentTreeNode(tl, tr) { |
| 15 | + this.sum = 0; |
| 16 | + this.left = null; |
| 17 | + this.right = null; |
| 18 | + this.tl = tl; // tree left boundary |
| 19 | + this.tr = tr; // tree right boundary |
| 20 | +} |
| 21 | + |
| 22 | +const build = (a, tl, tr) => { |
| 23 | + if (tl > tr) return null; |
| 24 | + let stn = new SegmentTreeNode(a[tl], a[tr]); |
| 25 | + if (tl == tr) return stn; |
| 26 | + let mid = (tl + tr) >> 1; |
| 27 | + stn.left = build(a, tl, mid); |
| 28 | + stn.right = build(a, mid + 1, tr); |
| 29 | + return stn; |
| 30 | +}; |
| 31 | + |
| 32 | +const update = (stn, newVal) => { |
| 33 | + if (stn == null) return; |
| 34 | + if (newVal >= stn.tl && newVal <= stn.tr) { |
| 35 | + stn.sum++; |
| 36 | + update(stn.left, newVal); |
| 37 | + update(stn.right, newVal); |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +const sumUtil = (stn, l, r) => { |
| 42 | + if (stn == null) return 0; |
| 43 | + if (l <= stn.tl && r >= stn.tr) return stn.sum; |
| 44 | + if (r < stn.tl || l > stn.tr) return 0; |
| 45 | + return sumUtil(stn.left, l, r) + sumUtil(stn.right, l, r); |
| 46 | +}; |
| 47 | + |
| 48 | +const countRangeSum = (a, lower, upper) => { |
| 49 | + let an = a.length; |
| 50 | + let pre = new Set(); |
| 51 | + let sum = 0; |
| 52 | + for (const e of a) { |
| 53 | + sum += e; |
| 54 | + pre.add(sum); |
| 55 | + } |
| 56 | + let u = [...pre]; |
| 57 | + let un = u.length; |
| 58 | + u.sort((x, y) => x - y); |
| 59 | + let root = build(u, 0, un - 1); |
| 60 | + let res = 0; |
| 61 | + for (let i = an - 1; ~i; i--) { |
| 62 | + update(root, sum); |
| 63 | + sum -= a[i]; |
| 64 | + res += sumUtil(root, lower + sum, upper + sum); |
| 65 | + } |
| 66 | + return res; |
| 67 | +}; |
0 commit comments