Find Cheapest Taxi Fare
Given an array of taxi fare quotes from different companies, find the cheapest fare. Return the minimum fare from the list. If the array is empty, return 0.
For example, the cheapest fare from [25, 18, 30, 22] is 18. From [40] it is 40. An empty array returns 0.
Finding the minimum value is the mirror image of finding the maximum and equally fundamental. Comparing prices to find the best deal is a ubiquitous real-world application: flight tickets, hotel rates, insurance premiums, and grocery prices all use this pattern.
The solution tracks a running minimum by comparing each fare against the current best. Initialize min to the first fare and update it whenever a lower fare is encountered. Return min after examining all options.
Edge cases include an empty array (return 0), a single fare (return it), and all equal fares (return that value). The algorithm correctly handles any ordering of the input.
Example Input & Output
30 is the lowest fare in the list.
With one taxi option, that fare is automatically the cheapest.
No fares means there is no valid answer.
Algorithm Flow

Solution Approach
Iterate through the array while tracking the minimum fare seen so far.
Handle the empty case by returning 0 immediately to avoid index errors. Initialize min to the first fare. Loop through each fare; if the current fare is less than min, update min. After examining all fares, return the minimum value found.
Time complexity is O(n), space complexity is O(1). The algorithm examines each fare exactly once, making it optimal.
Best Answers
program find_cheapest_taxi_fare
dictionary
fares: array[1..100] of integer
cheapest, i, n: integer
algorithm
input(fares)
n <- fares.length
if n = 0 then
output(-1)
else
cheapest <- fares[0]
for i <- 1 to n - 1 do
if fares[i] < cheapest then
cheapest <- fares[i]
endif
endfor
output(cheapest)
endif
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
