AlgoDaily

How to Find the Minimum and Maximum Value in An Array

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Introduction

In this tutorial, we'll learn to find out the minimum and maximum values in an array using the following techniques.

  • Built-in Methods
  • Linear Search Method
  • Divide and Conquer
  • Single Loop Trick/ Comparison in Pairs

We'll be using a few different languages to solve the problem. So without further ado, let's get started!

Min and Max in Array

Built-in methods

Built-in Methods

Rather than solving each and every problem manually, there are built-in methods available in programming languages which makes it easier for programmers to write code.

Let's have a look at the built-in methods available in Python, JavaScript, and Java to find the minimum and maximum value in an array.

  • Python has built-in functions min() and max() to find the minimum and maximum value in an array.
  • JavaScript has a built-in Math object that includes methods and constants for performing mathematical operations. We'll use Math.min() and Math.max() to find the minimum and maximum value in an array. Note that if we pass an array as an argument to these functions, it will return NaN. We can avoid this by using the spread operator to unwrap the elements.
  • In Java, we can use Collections.min() and Collections.max() methods. But since this method requires a list, so first, we'll convert an array to a list and then pass the list to these functions as an argument.

Now let's have a look at examples using the built-in methods available in these languages:

```py
def findMinimumAndMaximum(input):
    
    maximum = max(input);
    minimum = min(input)
    
    return (maximum,minimum)
    
if __name__ == "__main__":
    input = [ 1,4,100,9,456]
    maximum, minimum = findMinimumAndMaximum(input)
    print("Minimum value in an array is", minimum)
    print("Maximum value in an array is", maximum)
```
```js
 function findMinimumAndMaximum(input)
    {
        result = new  Array();
        result.maximum = Math.max(...input);
        result.minimum = Math.min(...input);
        
        return result;
    }
 
const input = [1,4,100,9,456];
result = findMinimumAndMaximum(input);
document.write("Minimum value in an array is ",result.minimum);
document.write("Maximum value in an array is ",result.maximum);
```
```java
import java.util.Arrays;
import java.util.Collections;

class MinimumAndMaximum{
    
    static class Result {
 
        int minimum;
        int maximum;
    }
    
     static Result findMinimumAndMaximum(Integer input[]) {
         
        Result result = new  Result();
        result.minimum = Collections.min(Arrays.asList(input));
        result.maximum = Collections.max(Arrays.asList(input));

        return result;
    }
    
    
    public static void main(String[] args) {
        Integer input[] = {1,4,100,9,456};
        Result result = findMinimumAndMaximum(input);
        System.out.printf("Minimum value in an array is " + result.minimum +"\n");
        System.out.printf("Maximum value in an array is " + result.maximum);
    }
}
```

Built-ins Data Flow

Before moving on, separate the call style from the idea.

All three languages are doing the same thing: send a collection of numbers into a library helper, then receive one extreme value back. The only difference is the wrapper needed by each language.

Built-ins Data Flow

Built-ins Mental Model

Built-in functions are the shortest path when the interview or task allows them: hand the whole array to the language/runtime, and receive the smallest or largest value back.

Notice one important difference in the visual: Python accepts the array directly, JavaScript needs the spread operator, and Java usually converts the array into a list first.

Built-ins Mental Model

Built-ins at a Glance

Before moving into manual algorithms, keep the built-in approach mentally simple: the language does the scan for you.

Notice the small syntax differences: Python accepts the array directly, JavaScript needs the spread operator, and Java commonly converts the array into a list before using Collections.min() and Collections.max().

Built-ins at a Glance

Multiple Choice

What is the name of Python's built-in function to find the maximum value in an array?

Linear Search Method

Linear Search Method

In the Linear Search method, we'll implement the following steps.

  • Initialize the minimum and maximum values to the first element of the array.
  • Traverse the array except for the first element.
  • Update the minimum and maximum values after comparing them with the values in the array on each iteration accordingly.

Let's have a look at the Pseudocode first:

Pseudocode
int[] findMinimumAndMaximum(int input[], int size)
{
    int maximum = input[0]
    int minimum = input[0]
    for ( i = 1 to size-1 )
    {
        if ( input[i] > maximum )
            maximum = input[i]
        else if ( input[i] < minimum )
            minimum = input[i]
    }
    int result[2] = {maximum, minimum}
    return result
}

Now, we'll implement the above steps in some other languages:

```py
def findMinimumAndMaximum(input, size):
    
    maximum = input[0]
    minimum = input[0]

    for i in range(1, size):
        if input[i] > maximum:
            maximum = input[i]
        elif input[i] < minimum:
            minimum = input[i]
 
    return (maximum,minimum)
    
if __name__ == "__main__":
    input = [ 1,4,100,9,456]
    maximum,minimum = findMinimumAndMaximum(input, len(input))
    print("Minimum value in an array is", minimum)
    print("Maximum value in an array is", maximum)
```
```js
function findMinimumAndMaximum(input, size)
    {
        result = new  Array();
        result.maximum = input[0];
        result.minimum = input[0];
        
 
        for (var i = 1; i < size; i++) {
            if (input[i] > result.maximum) {
                result.maximum = input[i];
            } else if (input[i] < result.minimum) {
                result.minimum = input[i];
            }
        }
 
        return result;
    }
var input = [1,4,100,9,456];
result = findMinimumAndMaximum(input, input.length);
document.write("Minimum value in an array is" ,result.minimum);
document.write("Maximum value in an array is" , result.maximum);
```
```java
class MinimumAndMaximum{
    
    static class Result {
 
        int minimum;
        int maximum;
    }
    
     static Result findMinimumAndMaximum(int input[], int size) {
        Result result = new  Result();
        result.minimum = input[0];
        result.maximum = input[0];
    
        for (int i = 1; i < size; i++) {
            if (input[i] > result.maximum) {
                result.maximum = input[i];
            } else if (input[i] < result.minimum) {
                result.minimum = input[i];
            }
        }
 
        return result;
    }
    
    
    public static void main(String[] args) {
       int input[] = {1,4,100,9,456};
        Result result = findMinimumAndMaximum(input, input.length);
        System.out.printf("Minimum value in an array is " + result.minimum +"\n");
        System.out.printf("Maximum value in an array is " + result.maximum);
    }
}
```

Multiple Choice

In the Linear Search method, the maximum and minimum value is initialized to the last element of the array.

Divide and Conquer

Divide and Conquer

In Divide and Conquer method, we'll implement the following steps.

  • Divide the array into two parts.
  • Find the minimum **and **maximum of both the parts recursively.
  • Take the **minimum **and **maximum **values of both the parts, compare them, and then find the **minimum **and **maximum **value of the entire array.

Next, we'll have a look at the Pseudocode:

Pseudocode
int[] findMinimumAndMaximum(int begin, int end,int input[])
{
    int maximum;
    int minimum;
    if ( begin == end )
    {
        minimum = input[begin]
        maximum = input[begin]
    }
    else if ( begin + 1 == end )
    {
        if ( input[begin] < input[end] )
        {
            minimum = input[begin]
            maximum = input[end]
        }
        else
        {
            minimum = input[end]
            maximum = input[begin]
        }
    }
    else
    {
        int midpoint = begin + (end - begin)/2
        int leftArray[] = findMinimumAndMaximum(begin, midpoint, input)
        int rightArray[] = findMinimumAndMaximum(midpoint+1, end, input)
        if ( leftArray[0] > rightArray[0] )
            maximum = leftArray[0]
        else
            maximum = rightArray[0]
        if ( leftArray[1] < rightArray[1] )
            minimum = leftArray[1]
        else
            minimum = rightArray[1]
    }

    int result[2] = {maximum, minimum}
   return result
}

Now let's head straight to the implementation in Python, JavaScript, and Java:

```py
def findMinimumAndMaximum(input, begin, end):
    maximum = input[begin]
    minimum = input[begin]
    
    if begin == end:
        minimum = input[begin]
        maximum = input[begin]
        return (maximum, minimum)
 
    elif begin + 1 == end:
        if input[begin] > input[end]:
            minimum = input[end]
            maximum = input[begin]
        else:
            minimum = input[begin]
            maximum = input[end]
        return (maximum, minimum)
    else:
        midpoint = int((begin + (end-begin)/2))
        maximum_l, minimum_l = findMinimumAndMaximum(input, begin, midpoint)
        maximum_r, minimum_r = findMinimumAndMaximum(input, midpoint + 1, end)
    return (max(maximum_l, maximum_r), min(minimum_l, minimum_r))
    
if __name__ == "__main__":  
    input = [1,4,100,9,456]
    end = len(input) - 1
    begin = 0
    maximum, minimum = findMinimumAndMaximum(input, begin, end)
    print('Minimum value in an array is ', minimum)
    print('Maximum value in an array is ', maximum)
```
```js
function findMinimumAndMaximum(input , begin , end) {
        result = new Array(); 
        var result_left = new Array();
        var result_right = new Array();
        var midpoint;
 
        if (begin == end) {
            result.maximum = input[begin];
            result.minimum = input[begin];
            return result;
        }
 
        if (begin + 1 == end) {
            if (input[begin] > input[end]) {
                result.maximum = input[begin];
                result.minimum = input[end];
            } else {
                result.maximum = input[end];
                 result.minimum  = input[begin];
            }
            return result;
        }
 
        midpoint = parseInt(begin+(end-begin)/2);
        result_left = findMinimumAndMaximum(input, begin , midpoint);
        result_right = findMinimumAndMaximum(input, midpoint + 1, end);
 
        if (result_left.minimum < result_right.minimum) {
            result.minimum = result_left.minimum;
        } else {
            result.minimum = result_right.minimum;
        }
 
        if (result_left.maximum > result_right.maximum) {
            result.maximum = result_left.maximum;
        } else {
            result.maximum = result_right.maximum;
        }
 
        return result;
    }
 
var input = [ 1,4,100,9,456 ];
result = findMinimumAndMaximum(input, 0, input.length - 1);
document.write("Minimum value in an array is ", result.minimum);
document.write("Maximum value in an array is ", result.maximum);
```
```java
public class MinimumAndMaximum {
    static class Result {
 
        int minimum;
        int maximum;
    }
 
    static Result findMinimumAndMaximum(int input[], int begin, int end)
    {
        Result result = new Result();
        Result result_left = new Result();
        Result result_right = new Result();
        int midpoint;
 
        if (begin == end) {
            result.maximum = input[begin];
            result.minimum = input[begin];
            return result;
        }
 
        if (begin+1 == end) {
            if (input[begin] > input[end]) {
                result.maximum = input[begin];
                result.minimum = input[end];
            }
            else {
                result.maximum = input[end];
                result.minimum = input[begin];
            }
            return result;
        }
 
        
        midpoint = begin+(end-begin)/2;
        result_left = findMinimumAndMaximum(input, begin, midpoint);
        result_right = findMinimumAndMaximum(input, midpoint + 1, end);
 
        
        if (result_left.minimum < result_right.minimum) {
            result.minimum = result_left.minimum;
        }
        else {
            result.minimum = result_right.minimum;
        }
 
        
        if (result_left.maximum > result_right.maximum) {
            result.maximum = result_left.maximum;
        }
        else {
            result.maximum = result_right.maximum;
        }
 
        return result;
    }
 
    public static void main(String args[])
    {
        int input[] = {1,4,100,9,456};
        Result result = findMinimumAndMaximum(input, 0, input.length - 1);
        System.out.printf("Minimum value in an array is "+
                          result.minimum+"\n");
        System.out.printf("Maximum value in an array is "+
                          result.maximum);
    }
}
```


Manual Strategy Map

You now have two manual ways to find the same answer.

Linear search keeps one running minimum and maximum while walking left to right. Divide and conquer splits the array, solves smaller ranges, then merges each range’s (max, min) result upward.

Manual Strategy Map

Manual Search Patterns

The manual methods all do the same job: keep track of a current minimum and maximum while proving that every value has been considered.

Use this visual to separate the two mental models: linear search walks left to right, while divide and conquer splits the array, solves smaller pieces, then merges the local min/max results.

Manual Search Patterns

Two Manual Strategies

Linear search and divide-and-conquer both inspect the same values, but they organize the work differently.

Use the visual to compare the mental models: linear search keeps one running minimum and maximum, while divide-and-conquer splits the array, solves smaller pieces, then combines the partial answers.

Two Manual Strategies

Multiple Choice

How many parts the array is divided into in Divide and Conquer method?

Single Loop Trick/Comparison in Pairs

Single Loop Trick/Comparison in Pairs

In the Comparison in Pairs method, we'll implement the following steps.

  • If the size of the array is odd, then we'll initialize the *minimum **and **maximum * values to the first element of the array.
  • If the size is even, then we'll compare the first and second elements of the array and initialize **minimum **and **maximum **values accordingly.
  • Next, we'll traverse the array in pairs.
  • After that, we'll find the minimum and **maximum **value of each pair and then update the **minimum **and **maximum **value of the entire array accordingly.

Let's have a look at the Pseudocode:

Pseudocode
int[] findMinimumAndMaximum(int input[], int size)
{
    int maximum, minimum
    int index
    if ( size % 2 ==0)
    {
      if ( input[0] < input[1] )
         {
            maximum = input[1]
            minimum = input[0]
         }
         else
         {
            maximum = input[0]
            minimum = input[1]
          }
       index = 2   
    }
    else
    {
        maximum = input[0]
        minimum = input[0]
        index = 1      
    }
    while ( index < size )
    {
        if ( input[index] < input[index+1] )
        {
            if ( input[index] < minimum )
                minimum = input[index]
            if ( input[index+1] > maximum )
                maximum = input[index+1]
        }
        else
        {
            if ( input[index] > maximum )
                maximum = input[index]
            if ( input[index+1] < minimum )
                minimum = input[index+1] 
        }
        index = index + 2
    }

    int result[2] = {maximum, minimum}
   return result
}

Next, we'll implement the above steps in Python, Javacript, and Java:

```py
def findMinimumAndMaximum(input,size):
    
    if(size % 2 == 0):
        maximum = max(input[0], input[1])
        minimum = min(input[0], input[1])
        index = 2
    else:
        maximum = minimum = input[0]
        index = 1
    while(index < size - 1):
        if input[index] < input[index + 1]:
            maximum = max(maximum, input[index + 1])
            minimum = min(minimum, input[index])
        else:
            maximum = max(maximum, input[index])
            minimum = min(minimum, input[index + 1])
        index += 2
     
    return (maximum, minimum)
if __name__ =='__main__':
    input = [1,4,100,9,456]
    maximum, minimum = findMinimumAndMaximum(input,len(input))
    print("Minimum value in an array is", minimum)
    print("Maximum value in an array is", maximum)
```
```js
function findMinimumAndMaximum(input, size){
    
    result = new Array(); 
    var index;
    if(size % 2 == 0){
        result.maximum = Math.max(input[0], input[1])
        result.minimum = Math.min(input[0], input[1])
        index = 2
    }
    else{
        result.maximum = result.minimum = input[0]
        index = 1
    }

    while(index < size - 1){
        if(input[index] < input[index + 1]){
            result.maximum = Math.max(result.maximum, input[index + 1])
            result.minimum = Math.min(result.minimum, input[index])
        }
        else{
            result.maximum = Math.max(result.maximum, input[index])
            result.minimum = Math.min(result.minimum, input[index + 1])
        }
        index += 2
    }
     
    return result
}

var input = [1,4,100,9,456]
result = findMinimumAndMaximum(input, input.length)
document.write("Minimum value in an array is", result.minimum)
document.write("Maximum value in an array is", result.maximum)
```
```java
public class MinimumAndMaximum {
     static class Result {
 
        int minimum;
        int maximum;
    }
 
    static Result findMinimumAndMaximum(int input[], int size) {
        Result result = new Result();
        int index;
        if (size % 2 == 0) {
            if (input[0] > input[1]) {
                result.maximum = input[0];
                result.minimum = input[1];
            } else {
                result.minimum = input[0];
                result.maximum  = input[1];
            }
            index = 2;
            
        } 
       else {
            result.minimum = input[0];
            result.maximum  = input[0];
            index = 1;
        }
        while (index < size - 1) {
            if (input[index] > input[index + 1]) {
                if (input[index] > result.maximum ) {
                    result.maximum  = input[index];
                }
                if (input[index + 1] < result.minimum) {
                    result.minimum = input[index + 1];
                }
            } else {
                if (input[index + 1] > result.maximum ) {
                    result.maximum  = input[index + 1];
                }
                if (input[index] < result.minimum) {
                    result.minimum = input[index];
                }
            }
            index += 2;
        }
 
        return result;
    }
 
    public static void main(String args[]) {
        int input[] = {1,4,100,9,456};
        Result result = findMinimumAndMaximum(input, input.length);
        System.out.printf("Minimum value in an array is "+result.minimum + "\n");
        System.out.printf("Maximum value in an array is "+result.maximum);
 
    }
}

```

Multiple Choice

If the array size is odd in Comparison in Pairs method, the maximum and minimum value is initialized to which element of the array?

Conclusion

Conclusion

With this, we have come to the end of our tutorial. Here, we learned to find out the minimum and maximum values in an array using the Built-in, Linear Search, Divide and Conquer, and Comparison in Pairs methods. We also implemented each method in Python, JavaScript, and Java.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • We will learn to find the maximum and minimum values in an array using built-in methods, linear search, divide and conquer and a single-loop trick in various languages.
  • Using the built-in methods of Python, JavaScript, and Java, we can easily determine the minimum and maximum value in an array.
  • - Built-ins hide the scan, but they still conceptually inspect the collection to return one extreme value.
  • - Built-ins hide the scan, but the input shape differs by language: min/max(array), Math.min/max(...array), or Collections.min/max(list).
  • - Built-ins hide the traversal, but each language has its own input shape requirements.
  • Python has two built-in functions, min() and max(), to find the minimum and maximum value in an array, respectively.
  • The Linear Search Method traverses an array from the second element to find the maximum and minimum values, which can be implemented using the Pseudocode provided and other languages to obtain the desired result.
  • The Linear Search algorithm's maximum and minimum values must be initialized to the first element of the array, as it traverses through the array from the beginning to find the maximum and minimum values.
  • The Divide and Conquer method can be used to find the minimum and maximum value of an array by recursively splitting it into two parts and comparing their results.
  • - Linear search updates extremes in one pass; divide and conquer combines extremes from smaller subarrays.
  • - Linear search scans once; divide and conquer splits, solves subarrays, then combines their min/max pairs.
  • - Linear search scans left to right; divide-and-conquer splits, solves, and merges min/max results.
  • The Divide and Conquer method divides the array into two parts of varying sizes, eventually resulting in the determination of the overall minimum and maximum values.
  • We can find the minimum and maximum values of an array using the Comparison in Pairs method which involves initializing the minimum and maximum values based on the size of the array and then traversing the array in pairs within a single loop.
  • The maximum and minimum value of the array is initialized to input[0], the first element, when the array size is odd.
  • We concluded the tutorial by learning the Built-in, Linear Search, Divide and Conquer, and Comparison in Pairs methods for finding minimum and maximum values in an array and implementing these methods in Python, JavaScript and Java.
Open interactive view →