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
23
class Solution {
 public:
  long long minimumTime(vector<int>& time, int totalTrips) {
    long long l = 1;
    long long r =
        *min_element(begin(time), end(time)) * static_cast<long>(totalTrips);

    while (l < r) {
      const long 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(begin(times), end(times), 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