Code Logo

Pick Cheapest Lunch

Published at19 Apr 2026
Logic & Conditionals Easy 6 views
Like0

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.

Learn about our pseudocode specification
Guide

Example Input & Output

Example 1
Input
prices = []
Output
-1
Explanation

No menu options means there is no valid cheapest price.

Example 2
Input
prices = [25, 18, 22, 30]
Output
18
Explanation

18 is the cheapest menu price in the list.

Example 3
Input
prices = [12]
Output
12
Explanation

With only one lunch option, that price is the answer.

Algorithm Flow

Recommendation Algorithm Flow for Pick Cheapest Lunch

Solution Approach

Iterate through the list and track the smallest price seen so far.

if list is empty then return 0
min = list[0]
for each price in list:
  if price < min then min = price
return min

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

Pseudocode - Approach 1
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
endprogram