Leetcode 2739. Total Distance Traveled
You are given an integer trips
which represents the number of trips a car needs to make.
To complete a single trip, the car starts at milesStart
and travels to milesEnd
and back to milesStart
. It continues this journey for trips
number of times.
Write a function totalDistance
that calculates the total distance traveled by the car for all the trips.
Function Signature:
int totalDistance(int milesStart, int milesEnd, int trips);
milesStart
and milesEnd
always be positive integers?
int
in C++.trips
is 0?
trips
is 0, it should return 0 since no trips mean no distance traveled.milesEnd
and back to milesStart
for each trip.distance_per_trip = 2 * (milesEnd - milesStart)
This captures the travel from milesStart
to milesEnd
and back from milesEnd
to milesStart
.
total_distance = distance_per_trip * trips
trips
is 0, return 0 as no travel occurs.Here is the C++ function to accomplish this:
#include <iostream>
int totalDistance(int milesStart, int milesEnd, int trips) {
// Special case: when 0 trips, distance traveled is 0.
if (trips == 0)
return 0;
// Calculate the distance for one round trip.
int distance_per_trip = 2 * (milesEnd - milesStart);
// Total distance is the distance per trip times the number of trips.
int total_distance = distance_per_trip * trips;
return total_distance;
}
int main() {
// Example usage:
int milesStart = 10;
int milesEnd = 20;
int trips = 5;
int result = totalDistance(milesStart, milesEnd, trips);
std::cout << "Total distance traveled: " << result << std::endl; // Should print 100
return 0;
}
The time complexity of the solution is O(1) since the calculations involve only a few arithmetic operations, making it constant in terms of execution time regardless of input values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?