Payments app~25 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-120dp
A payments app sends each payment through layers of partner banks. The first layer has one bank, the next has two, and each layer has one more than the one before. Every bank charges a fee.
A payment at position c of a layer can pass to position c or c + 1 of the next layer. Your team lead asks: "What is the least total fee of any route from the first layer to the last?"
Write least_total_fee(triangle).
triangle[r] lists the fees of layer r, which has r + 1 banks. Layer 0 has one bank.c of layer r it passes to position c or c + 1 of layer r + 1.Input: triangle = [[5], [2, 6], [7, 3, 4], [1, 8, 2, 9]]
Output: 12Work from the last layer upwards. Let best[r][c] be the least total fee from bank (r, c) down to the last layer. In the last layer it is the bank's own fee. Above it, take the cheaper of the two banks below and add this fee.
| Layer | Position 0 | Position 1 | Position 2 | Position 3 |
|---|---|---|---|---|
| 3 | 1 (last layer) | 8 (last layer) | 2 (last layer) | 9 (last layer) |
| 2 | 8 (7 + min(1, 8)) | 5 (3 + min(8, 2)) | 6 (4 + min(2, 9)) | |
| 1 | 7 (2 + min(8, 5)) | 11 (6 + min(5, 6)) | ||
| 0 | 12 (5 + min(7, 11)) |
The top holds 12, so the least total fee is 12.
Input: triangle = [[8]]
Output: 8One layer with one bank: the route is that bank, so the fee is 8.
Input: triangle = [[1], [9, 2], [9, 9, 9]]
Output: 12The cheapest route takes 1, then 2, then 9: 12.
1 ≤ len(triangle) ≤ 500, and triangle[r] has exactly r + 1 fees.0 ≤ triangle[r][c] ≤ 1,000There can be 500 layers, and each step has 2 choices, so about 2 to the power 499 routes exist. A table with one entry for each bank holds about 125,000 entries, and each takes a small step.