1767. Linear Boost Chain
A game has n power-up machines. Machine i transforms a score x into a[i] * x + b[i]. You start with the score 1, then choose exactly k different machines and send the score through them one after another, in any order you like. Each chosen machine is used once.
Return the largest final score you can reach. The result can exceed 32 bits, so return a long. Hint: for two machines i and j, using i first is at least as good as using j first exactly when b[i] * (a[j] - 1) >= b[j] * (a[i] - 1), so sort the machines by that rule and then run a table over how many machines have been used. Aim for O(n log n + n * k) time and O(n + k) space.
Example 1
- Input:
- a = [2,3], b = [1,1], k = 2
- Output:
- 10
- Explanation:
Using machine 0 first gives 2*1+1 = 3 and then machine 1 gives 3*3+1 = 10; the other order only reaches 9.
Example 2
- Input:
- a = [1,5,2], b = [9,1,3], k = 1
- Output:
- 10
- Explanation:
With one machine the options are 1+9 = 10, 5+1 = 6 and 2+3 = 5, so the best is 10.
Example 3
- Input:
- a = [1,1,1], b = [1,2,3], k = 3
- Output:
- 7
- Explanation:
All machines only add, so using all three gives 1 + 1 + 2 + 3 = 7 in any order.
Constraints
1 ≤ n ≤ 105, where n = a.length = b.length
1 ≤ k ≤ min(10, n)
1 ≤ a[i], b[i] ≤ 10
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n log n + n * k)
- Space
- O(n + k)