Maximum Number of Potholes That Can Be Fixed Problem
Description
LeetCode Problem 3119.
You are given a string road, consisting only of characters "x" and ".", where each "x" denotes a pothole and each "." denotes a smooth road, and an integer budget.
In one repair operation, you can repair n consecutive potholes for a price of n + 1.
Return the maximum number of potholes that can be fixed such that the sum of the prices of all of the fixes doesn't go over the given budget.
Example 1:
Input: road = "..", budget = 5
Output: 0
Explanation:
There are no potholes to be fixed.
Example 2:
Input: road = "..xxxxx", budget = 4
Output: 3
Explanation:
We fix the first three potholes (they are consecutive). The budget needed for this task is 3 + 1 = 4.
Example 3:
Input: road = "x.x.xxx...x", budget = 14
Output: 6
Explanation:
We can fix all the potholes. The total cost would be (1 + 1) + (1 + 1) + (3 + 1) + (1 + 1) = 10 which is within our budget of 14.
Constraints:
1 <= road.length <= 10^51 <= budget <= 10^5 + 1roadconsists only of characters'.'and'x'.
Solution
Approach: Counting + Greedy
Count the runs of consecutive potholes: cnt[k] is the number of runs of length k. Repairing a run of length k costs k + 1, so longer runs are the better deal (the extra 1 is amortised over more potholes).
Go from the longest length down. For length k, repair t = min(budget / (k + 1), cnt[k]) runs, add t * k to the answer and subtract t * (k + 1) from the budget. A run can also be repaired partially: with the leftover budget, shrinking a run to length k - 1 costs k, so the cnt[k] - t unrepaired runs are added to cnt[k - 1] and handled in the next step. Stop when the budget is used up.
Complexity: O(n) time and space, where n is the length of the road.
class Solution:
def maxPotholes(self, road: str, budget: int) -> int:
road += "."
n = len(road)
cnt = [0] * n
k = 0
for c in road:
if c == "x":
k += 1
elif k:
cnt[k] += 1
k = 0
ans = 0
for k in range(n - 1, 0, -1):
if cnt[k] == 0:
continue
t = min(budget // (k + 1), cnt[k])
ans += t * k
budget -= t * (k + 1)
if budget == 0:
break
cnt[k - 1] += cnt[k] - t
return ans