Pick Cheapest Lunch
Given an array of lunch prices, find the cheapest option. Return the minimum price from the list. If the array is empty, return 0.
For example, the cheapest lunch from [5, 3, 8, 2, 6] is 2. From [10, 20] it is 10. From a single price [7] it is 7. An empty list returns 0.
Finding the minimum value in a collection is a fundamental algorithmic pattern. It is used everywhere from data analysis (lowest temperature, smallest transaction) to algorithm design (priority queues, sorting, optimization). The pattern teaches you to initialize a candidate value and update it whenever a smaller value is encountered during iteration.
The solution initializes a variable with the first element (or a large sentinel value like infinity), then iterates through each price. If the current price is less than the stored minimum, update the minimum. After the loop, return the minimum value. This runs in O(n) time with O(1) space.
Edge cases include an empty array (return 0), a single-element array (return that element), and an array where all prices are equal (return that value). Negative prices are not expected, but the algorithm handles them naturally.
Example Input & Output
No menu options means there is no valid cheapest price.
18 is the cheapest menu price in the list.
With only one lunch option, that price is the answer.
Algorithm Flow
Solution Approach
Iterate through the list and track the smallest price seen so far.
First handle the empty list case by returning 0 immediately. Then initialize min to the first price. Loop through each remaining price; if the current price is smaller than min, update min. After examining all prices, return the min value found. This guarantees the minimum is correctly identified regardless of where it appears in the list.
The algorithm runs in O(n) time with O(1) extra space. It is optimal because every price must be examined at least once to guarantee the minimum has been found. The same pattern works for finding the maximum by simply reversing the comparison operator.
Best Answers
program pick_cheapest_lunch
dictionary
prices: array[1..100] of integer
cheapest, i, n: integer
algorithm
input(prices)
n <- prices.length
if n = 0 then
output(-1)
else
cheapest <- prices[0]
for i <- 1 to n - 1 do
if prices[i] < cheapest then
cheapest <- prices[i]
endif
endfor
output(cheapest)
endif
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
