mediumDynamic ProgrammingPattern: DP
Optimal Page Restoration Cost Solution
Problem Statement
You are given an array of integers `pageCounts` representing the number of pages in each book and an integer `budget` representing the maximum cost. Determine the minimum cost to restore as many pages as possible, where the cost of restoring the first page of each book is 10 units and each subsequent page costs 2 more units than the previous one.
Examples
Example 1:
Input:[3, 2, 1], 30
Output:31
Explanation: Restore the first 3 pages of the first book and the first page of the second book costs 27 + 30 + 33 = 90 which exceeds the budget, so restore the first page of each book costs 27 + 27 + 27 = 81 which exceeds the budget, so restore the first page of the first two books costs 27 + 27 = 54 which exceeds the budget, so restore the first page of the first book costs 27, which does not exceed the budget, so the minimum cost to restore as many pages as possible is 27
Example 2:
Input:[1, 1, 1], 10
Output:0
Explanation: The cost of restoring the first page of each book is 27, which exceeds the budget, so the minimum cost to restore as many pages as possible is 0
Constraints
- 1 <= pageCounts.length <= 100
- 1 <= pageCounts[i] <= 100
- 1 <= budget <= 10000
- The cost of restoring pages does not exceed the budget
- The input array is not empty
Time: O(n*b) Space: O(n*b)
An optimized approach uses dynamic programming to build up a table of minimum costs for restoring pages in each book, taking into account the increasing cost per page. This approach solves the problem in a bottom-up manner, iterating through each book and each possible number of pages to restore. The time complexity of this approach is O(n*b), where n is the number of books and b is the budget.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
pageCounts = list(map(int, input().split()))
budget = int(input())
dp = [0] * (budget + 1)
for i in range(len(pageCounts)):
cost = 10
pages = 0
for j in range(pageCounts[i], 0, -1):
if cost > budget: break
for k in range(budget, cost - 1, -1):
dp[k] = max(dp[k], dp[k - cost] + j)
cost += 2
pages += 1
print(max(dp))