Skip to content

2187. Minimum Time to Complete Trips 👍

  • Time: $O(n\log (\min(\texttt{time}) \cdot \texttt{totalTrips}))$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  long long minimumTime(vector<int>& time, int totalTrips) {
    long l = 1;
    long r = static_cast<long>(ranges::min(time)) * totalTrips;

    while (l < r) {
      const long m = (l + r) / 2;
      if (numTrips(time, m) >= totalTrips)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  long numTrips(const vector<int>& times, long m) {
    return accumulate(times.begin(), times.end(), 0L,
                      [&](long subtotal, int t) { return subtotal + m / t; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public long minimumTime(int[] time, int totalTrips) {
    long l = 1;
    long r = Arrays.stream(time).min().getAsInt() * (long) totalTrips;

    while (l < r) {
      final long m = (l + r) / 2;
      if (numTrips(time, m) >= totalTrips)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  private long numTrips(int[] time, long m) {
    return Arrays.stream(time).asLongStream().reduce(0L, (subtotal, t) -> subtotal + m / t);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minimumTime(self, time: list[int], totalTrips: int) -> int:
    l = 1
    r = min(time) * totalTrips

    while l < r:
      m = (l + r) // 2
      if sum(m // t for t in time) >= totalTrips:
        r = m
      else:
        l = m + 1

    return l