Payments app~25 min2s · 256 MBtarget O(n³) time, O(n²) spaceclassic twin: lc-375dp
A payments app has a hidden invoice number from 1 to n. A support agent finds it by guessing. After each wrong guess the app only says whether the hidden number is higher or lower.
A wrong guess of g costs g units in processing fees, and the correct guess is free. Your team lead asks: "What is the smallest budget that is enough to find the number, whichever number is hidden?"
Write least_guaranteed_cost(n).
n, and the agent does not know which.g, the agent learns whether the number is below or above g. The wrong guess costs g units.Input: n = 5
Output: 6Let cost[lo][hi] be the smallest budget that guarantees finding a number known to be between lo and hi. An empty or single-number range costs 0. For a longer range, guess some k, pay k, and then the hidden number sits in the more expensive of the two sides left.
Try every k and keep the least. We fill ranges from short to long.
| Length | Range | cost |
|---|---|---|
| 2 | 1 to 2, 2 to 3, 3 to 4, 4 to 5 | 1, 2, 3, 4 |
| 3 | 1 to 3, 2 to 4, 3 to 5 | 2, 3, 4 |
| 4 | 1 to 4, 2 to 5 | 4, 6 |
| 5 | 1 to 5 | 6 |
For range 1 to 5, guessing k = 1, 2, 3, 4, 5 costs 7, 6, 7, 6, 9. The least is 6. For example, k = 4 pays 4, and the worse side is the range 1 to 3, which costs 2, so the total is 6.
Input: n = 1
Output: 0Only one number is possible, so the agent needs no wrong guess.
Input: n = 2
Output: 1Guess 1. If it is wrong, the hidden number is 2, and the cost was 1. Guessing 2 first would cost 2.
1 ≤ n ≤ 200The agent can choose from n guesses in a range, and each reply leaves a smaller range, so the number of strategies explodes. A table over ranges has about n²/2 entries, and each tries up to n guesses. That is 1,353,200 steps for n = 200, which is small.