Bank app~40 min4s · 256 MBtarget O((n + q) sqrt(n log n)) time, O(n) spacebinary-search
You work on a banking app. A bank holds up to 20,000 accounts, numbered in a fixed order, and each account has a balance in units. A bonus credits the same amount to every account in a range of numbers.
Between bonuses, the product team asks how many accounts in a range hold at least a given balance. Your team lead asks: "Can we answer after every bonus without visiting every account?" There are up to 20,000 operations.
Write count_at_least(balances, ops).
balances[i] is the balance of account i, in units.[kind, l, r, x].[0, l, r, x] is a bonus: add x units to every account from l to r, both included.[1, l, r, x] is a question: count the accounts from l to r whose balance is at least x.Input: balances = [5, 1, 4, 2, 8, 3, 7, 6, 9, 0, 2, 5], ops = [[0, 2, 9, 3], [1, 1, 10, 8], [1, 4, 7, 10]]
Output: [4, 2]| Operation | Balances after it | Answer |
|---|---|---|
[0, 2, 9, 3] |
5, 1, 7, 5, 11, 6, 10, 9, 12, 3, 2, 5 | |
[1, 1, 10, 8] |
accounts 1 to 10: 1, 7, 5, 11, 6, 10, 9, 12, 3, 2 | 4 (11, 10, 9, 12) |
[1, 4, 7, 10] |
accounts 4 to 7: 11, 6, 10, 9 | 2 (11, 10) |
Input: balances = [3], ops = [[1, 0, 0, 3], [0, 0, 0, 2], [1, 0, 0, 6]]
Output: [1, 0]A balance of 3 meets the threshold 3. After a bonus of 2 the balance is 5, which is below 6.
Input: balances = [0, 0, 0, 0], ops = [[1, 0, 3, 0], [1, 1, 2, 1]]
Output: [4, 0]Every balance is at least 0, so all 4 accounts count. No balance reaches 1.
1 ≤ len(balances) ≤ 20,0000 ≤ balances[i] ≤ 1,000,0001 ≤ len(ops) ≤ 20,000kind is 0 or 1 and 0 ≤ l ≤ r < len(balances).0 ≤ x ≤ 1,000. For a question, 0 ≤ x ≤ 100,000,000.Touching every account of a range costs up to 20,000 steps, and 20,000 operations cost 400 million steps. That is too slow. A segment tree adds to a range easily but cannot count values above a threshold. Blocks of about 200 accounts, each with a sorted copy, cost a few thousand steps for each operation.