Payments app~20 min2s · 256 MBtarget O(q (m + n)) time, O(1) spaceclassic twin: lc-1351binary-search
A payments app keeps a settlement table. Row i is a group of merchants, column j is a fee plan, and the cell is the net amount in units after fees, which can be negative.
The amounts never rise as you move right or down: a higher fee plan or a larger merchant group never pays more. Finance asks many questions about the top-left corner of the table. For the first r merchant groups and the first c fee plans, how many cells lose money?
Write count_losses(nets, blocks).
nets[i][j] is the net amount in row i and column j. Along every row, from left to right, the amounts never rise. Along every column, from top to bottom, they never rise.blocks[k] = [r, c] asks about the cells in the first r rows and the first c columns.Input: nets = [[9, 5, 2, -1], [7, 4, 0, -3], [3, -2, -4, -6], [-1, -5, -7, -9]], blocks = [[4, 4], [2, 3], [3, 2], [1, 1], [4, 1], [2, 4]]
Output: [9, 0, 1, 0, 1, 2]Take the block [4, 4], the whole table. Start in the top-right corner, row 0, column 3. If the entry is negative, every entry below it in the column is negative too: add them all and move left. Otherwise move down.
| Step | Row | Column | Entry | Decision |
|---|---|---|---|---|
| 1 | 0 | 3 | -1 | negative, so the 4 entries from row 0 down in this column are negative: count 4, move left |
| 2 | 0 | 2 | 2 | not negative, so the entries to its left in this row are not negative either: move down |
| 3 | 1 | 2 | 0 | not negative, so the entries to its left in this row are not negative either: move down |
| 4 | 2 | 2 | -4 | negative, so the 2 entries from row 2 down in this column are negative: count 6, move left |
| 5 | 2 | 1 | -2 | negative, so the 2 entries from row 2 down in this column are negative: count 8, move left |
| 6 | 2 | 0 | 3 | not negative, so the entries to its left in this row are not negative either: move down |
| 7 | 3 | 0 | -1 | negative, so the 1 entry from row 3 down in this column are negative: count 9, move left |
The walk ends when the column goes below 0. The count is 9. The block [2, 3] holds 9, 5, 2, 7, 4 and 0, so its count is 0.
Input: nets = [[5]], blocks = [[1, 1]]
Output: [0]A table with one cell that is not negative has no loss.
Input: nets = [[3, -1], [-2, -4]], blocks = [[2, 2], [1, 2], [2, 1]]
Output: [3, 1, 1]In the whole table, 3 of the 4 cells are negative. The first row holds one negative cell, and the first column holds one.
nets has m rows and n columns, with 1 ≤ m, n ≤ 500, so up to 250,000 cells-1,000,000 ≤ nets[i][j] ≤ 1,000,0000 ≤ blocks.length ≤ 2,000, and for each block 1 ≤ r ≤ m and 1 ≤ c ≤ nReading every cell of a block costs up to 250,000 steps, and 2,000 blocks make 5 × 10^8 steps. The table is sorted in two directions. So one walk of at most r + c steps decides a whole block: about 1,000 steps a block and 2 × 10^6 in all.