Maximum Value

Another “classic” programming interview question.

The Question

Given user input of a series of numbers, find the maximum value of said input.

The Answer

This question is simple if you understand the concept behind arrays (which you can see the basics of in the “Reverse a Sentence” post).

The basic idea is to read the user input into an array with each number in the input separated into its own element in the array (the read -a numbers_array line).

Once the numbers are in the array, we want to iterate through each of the elements and check if the current element is larger than the current maximum element. If it is, then we want to override the previous maximum with the new maximum. Note that it is important that the initial maximum value is either not specified or set as one of the elements in the array at the start. This prevents errors if the user number list range does not encompass the initial maximum value.

If you comment out the lines (#echo “Current number/max) near the bottom, you can watch as the script compared the numbers and sets the maximum value.

#!/bin/bash
#set -xv

read -a numbers_array <<< "$1"

max_value="${numbers_array[1]}"

for (( i=0; i<"${#numbers_array[@]}"; i++ ))

do
     if (( "${numbers_array[i]}" > "$max_value" ))
     then
          max_value="${numbers_array[i]}"
     fi

     #echo "Current number: ${numbers_array[i]}"
     #echo "Current max: $max_value"

done

echo "Max value is: $max_value"

The output from the script will be as follows.

$ ./maximum_value "1 3 543 439293 11 12303403 3 3 2 8 4 2 2 6 7 7 043032 23 3 3 23 6 2 1 -543 1 -2 2 3 4 -2 3 321 756"
Max value is: 12303403
Tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam