Bank app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-135greedy
You work on a bank app that gives a loyalty bonus to the accounts of one branch. The accounts are in a row, and each has a rating from the last review.
Every account gets at least 1 bonus unit. An account with a higher rating than a neighbour next to it must get more units than that neighbour. Your team lead asks: "What is the fewest total bonus units that follows these rules?"
Write fewest_bonus_units(ratings).
ratings[i] is the rating of account i. The accounts are in a row, and account i is next to accounts i - 1 and i + 1.ratings[i] > ratings[i - 1], account i gets more units than account i - 1. If ratings[i] > ratings[i + 1], account i gets more units than account i + 1.Input: ratings = [3, 1, 4, 1, 5, 9, 2]
Output: 12Make two passes. From the left, an account with a higher rating than its left neighbour gets one more than that neighbour. From the right, do the same, and keep the larger of the two values.
| Account | Rating | After the left pass | After the right pass |
|---|---|---|---|
| 0 | 3 | 1 | 2 |
| 1 | 1 | 1 | 1 |
| 2 | 4 | 2 | 2 |
| 3 | 1 | 1 | 1 |
| 4 | 5 | 2 | 2 |
| 5 | 9 | 3 | 3 |
| 6 | 2 | 1 | 1 |
The units are 2, 1, 2, 1, 2, 3, 1, and they add up to 12.
Input: ratings = [5, 5, 5]
Output: 3Equal ratings have no rule between them, so each account gets 1 unit.
Input: ratings = [4, 3, 2, 1]
Output: 10Each rating is higher than the next one, so the units are 4, 3, 2, 1, which add up to 10.
1 ≤ len(ratings) ≤ 100,0001 ≤ ratings[i] ≤ 1,000,000There can be 100,000 accounts. Trying every assignment of units to accounts is n^n possibilities. Two passes cost 200,000 steps. The total can reach about 5 billion for a rising row, which is more than a 32-bit number holds, so use 64 bits.