Maximum Number of Potholes That Can Be Fixed - Problem
You're a road maintenance engineer with a limited budget who needs to fix as many potholes as possible on a damaged road. The road is represented as a string where 'x' represents a pothole and '.' represents smooth pavement.
Here's the key constraint: You can only repair consecutive potholes in a single operation. To repair n consecutive potholes costs n + 1 dollars (there's a fixed setup cost plus the cost per pothole).
Goal: Determine the maximum number of potholes you can fix without exceeding your budget.
Example: Road "x.xxx..x" has pothole groups of sizes [1, 3, 1]. Fixing 1 pothole costs 2, fixing 3 consecutive potholes costs 4, etc.
Input & Output
example_1.py โ Basic Case
$
Input:
road = "x.xxx.x", budget = 7
โบ
Output:
4
๐ก Note:
We have pothole groups of sizes [1, 3, 1]. We can repair the group of size 3 (cost 4) and one group of size 1 (cost 2), totaling 4 potholes for cost 6, which is within budget 7.
example_2.py โ Limited Budget
$
Input:
road = "xxx.x.x", budget = 4
โบ
Output:
3
๐ก Note:
We have groups [3, 1, 1]. We can either repair the group of size 3 (cost 4) or two groups of size 1 (cost 2+2=4). Repairing the size-3 group gives us 3 potholes, which is better than 2 potholes from the two size-1 groups.
example_3.py โ Edge Case
$
Input:
road = ".....", budget = 10
โบ
Output:
0
๐ก Note:
The road has no potholes, so we can't repair anything regardless of budget.
Constraints
- 1 โค road.length โค 104
- 1 โค budget โค 106
-
road consists only of characters
'.'and'x' - Each repair operation must fix consecutive potholes
Visualization
Tap to expand
Understanding the Visualization
1
Identify Segments
Parse the road to find all consecutive pothole groups
2
Calculate Efficiency
Smaller groups have better pothole-to-cost ratios due to fixed setup cost
3
Greedy Selection
Always choose the most efficient option first
4
Maximize Repairs
Continue until budget is exhausted
Key Takeaway
๐ฏ Key Insight: Due to the fixed setup cost, smaller pothole groups are more cost-efficient. The greedy approach of always choosing the most efficient option first guarantees the optimal solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code