Skip to content

3119. Maximum Number of Potholes That Can Be Fixed 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  int maxPotholes(string road, int budget) {
    int ans = 0;

    for (const int length : getSortedPotholeLengths(road)) {
      const int canRepair = max(0, budget - 1);
      if (length > canRepair)
        return ans + canRepair;
      ans += length;
      budget -= length + 1;
    }

    return ans;
  }

 private:
  vector<int> getSortedPotholeLengths(const string& road) {
    vector<int> potholeLengths;
    istringstream iss(road);
    string pothole;

    while (getline(iss, pothole, '.'))
      potholeLengths.push_back(pothole.length());

    ranges::sort(potholeLengths, greater<>());
    return potholeLengths;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxPotholes(String road, int budget) {
    int ans = 0;

    for (final int length : getSortedPotholeLengths(road)) {
      final int canRepair = Math.max(0, budget - 1);
      if (length > canRepair)
        return ans + canRepair;
      ans += length;
      budget -= length + 1;
    }

    return ans;
  }

  private List<Integer> getSortedPotholeLengths(final String road) {
    List<Integer> potholeLengths = new ArrayList<>();
    for (String pothole : road.split("\\."))
      potholeLengths.add(pothole.length());
    Collections.sort(potholeLengths, Collections.reverseOrder());
    return potholeLengths;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxPotholes(self, road: str, budget: int) -> int:
    ans = 0

    for length in sorted(map(len, road.split('.')), reverse=True):
      canRepair = max(0, budget - 1)
      if length > canRepair:
        return ans + canRepair
      ans += length
      budget -= length + 1

    return ans