Maximum Number of Potholes That Can Be Fixed - Problem

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.

Input & Output

Example 1 — Basic Road Repair
$ Input: road = ".xx.xxx.x", budget = 7
Output: 5
💡 Note: We have segments [2,3,1] with costs [3,4,2]. Best strategy: select segments of length 3 (cost 4) and length 2 (cost 3), total cost = 7, total potholes = 5
Example 2 — Limited Budget
$ Input: road = "...x.xx.xxx..", budget = 5
Output: 3
💡 Note: Segments [1,2,3] with costs [2,3,4]. We can afford segment of length 3 (cost 4) for maximum potholes, or segments [1,2] (cost 5). Both give 3 potholes
Example 3 — No Budget
$ Input: road = "xx.xx", budget = 1
Output: 0
💡 Note: Segments [2,2] both cost 3 each, but budget is only 1. Cannot afford any repairs

Constraints

  • 1 ≤ road.length ≤ 105
  • 1 ≤ budget ≤ 106
  • road consists only of characters '.' and 'x'

Visualization

Tap to expand
Maximum Potholes Repair ProblemInput: Road = ".xx.xxx.x", Budget = 7.xx.xxx.xStep 1: Find consecutive pothole segmentsSeg1: 2 holesSeg2: 3 holesSeg3: 1 holeStep 2: Calculate costs (length + 1)Cost: 3Cost: 4Cost: 2Step 3: Select optimal segments within budgetSelected: 3Selected: 2Output: 5 potholes fixed
Understanding the Visualization
1
Input
Road with potholes 'x' and budget constraint
2
Find Segments
Group consecutive potholes into repair segments
3
Optimal Selection
Choose most efficient segments within budget
Key Takeaway
🎯 Key Insight: Greedy selection by efficiency (potholes per dollar) gives optimal solution
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
24.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen