Skip to content

1936. Add Minimum Number of Rungs 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int addRungs(vector<int>& rungs, int dist) {
    int ans = 0;
    int prev = 0;

    for (const int rung : rungs) {
      ans += (rung - prev - 1) / dist;
      prev = rung;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int addRungs(int[] rungs, int dist) {
    int ans = 0;
    int prev = 0;

    for (final int rung : rungs) {
      ans += (rung - prev - 1) / dist;
      prev = rung;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def addRungs(self, rungs: list[int], dist: int) -> int:
    ans = 0
    prev = 0

    for rung in rungs:
      ans += (rung - prev - 1) // dist
      prev = rung

    return ans