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 That Can Be Fixed INPUT Road String Visualization: . 0 x 1 x 2 . 3 x 4 x 5 x 6 . 7 x 8 x = Pothole . = Smooth Pothole Groups Found: xx (2) xxx (3) x (1) road = ".xx.xxx.x" budget = 7 Total potholes: 6 ALGORITHM STEPS 1 Find Pothole Groups Groups: [3, 2, 1] (sizes) 2 Sort by Size (Desc) Sorted: [3, 2, 1] 3 Greedy Selection Pick largest groups first Cost Calculation (n+1) Group Cost Running xxx(3) 3+1=4 4 xx(2) 2+1=3 7 x(1) 1+1=2 9 (skip) 4 Count Fixed Fixed: 3 + 2 = 5 potholes Budget: 7/7 used FINAL RESULT Road After Repairs: . . . . . . . . x unfixed Fixed pothole Unfixed Summary Groups fixed: 2 (xxx, xx) Total cost: 4 + 3 = 7 Budget remaining: 0 Output: 5 OK - Maximum achieved! Key Insight: Greedy by efficiency: Larger consecutive pothole groups are more cost-effective to repair. Repairing n potholes costs n+1, so fixing 3 potholes (cost 4) is better value than 3 single repairs (cost 6). Sort groups by size descending and greedily pick until budget is exhausted. TutorialsPoint - Maximum Number of Potholes That Can Be Fixed | Greedy Approach
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