Bank app~25 min2s · 256 MBtarget O((n + q) log n) time, O(n) spacefenwick-tree
You work on a banking app that shows savings pots. A pot has the total deposited on each day, in whole units, counted from day 0. Late deposits can be back-dated to an earlier day.
A customer sets a goal. The app shows the first day on which the running total of deposits reached it. A pot can span 100,000 days and receive 100,000 operations.
Write earliest_goal_day(deposits, ops).
deposits[d] is the amount deposited on day d.ops is a list of operations in time order.[0, d, x] adds a late deposit of x to day d.[1, goal] is a question: what is the first day d such that the deposits of days 0 to d add up to at least goal? Answer -1 when even the whole pot is short.Input: deposits = [4, 0, 3, 5, 2], ops = [[1, 7], [0, 1, 6], [1, 7], [0, 4, 10], [1, 25], [1, 100]]
Output: [2, 1, 4, -1]Apply the operations in order. A late deposit raises every running total from its day onwards, so a goal can be reached earlier than before.
| Operation | Deposits afterwards | Running totals | Answer |
|---|---|---|---|
| First day to reach 7 | [4, 0, 3, 5, 2] | [4, 4, 7, 12, 14] | 2 |
| Add 6 to day 1 | [4, 6, 3, 5, 2] | [4, 10, 13, 18, 20] | none |
| First day to reach 7 | [4, 6, 3, 5, 2] | [4, 10, 13, 18, 20] | 1 |
| Add 10 to day 4 | [4, 6, 3, 5, 12] | [4, 10, 13, 18, 30] | none |
| First day to reach 25 | [4, 6, 3, 5, 12] | [4, 10, 13, 18, 30] | 4 |
| First day to reach 100 | [4, 6, 3, 5, 12] | [4, 10, 13, 18, 30] | -1 |
The answers are the figures in the last column: 2, 1, 4, -1.
Input: deposits = [0, 0, 0], ops = [[1, 0], [1, 1], [0, 2, 1], [1, 1]]
Output: [0, -1, 2]A goal of 0 is met on day 0. A goal of 1 cannot be met by an empty pot, until a late deposit of 1 arrives on day 2.
Input: deposits = [5], ops = [[1, 5], [1, 6]]
Output: [0, -1]A pot of 5 meets a goal of 5 on day 0, and cannot meet 6.
1 ≤ len(deposits) ≤ 100,0000 ≤ deposits[d] ≤ 1,000,0001 ≤ len(ops) ≤ 100,0000 ≤ d < len(deposits) and 0 ≤ x ≤ 1,000,000,000. A goal is between 0 and 1,000,000,000.Adding up the days from day 0 for each question reads up to 100,000 days, so 100,000 questions can read 10 billion. A table of running totals answers a question quickly with a search, but a late deposit then changes up to 100,000 running totals. You need a structure where both a deposit and the search for the goal day cost about 17 steps.