Find min and max together

Find min and max together

Easy Java Variables 29 views
Explanation Complexity

Problem Statement

Task: return [min,max] in one pass using two variables.

Input Format

An integer n
Then n integers

Output Format

An array [min, max]

Example

5
8 3 12 -4 7
[-4, 12]

Constraints

• n ≥ 1

• Must use single loop

Concept Explanation

We keep two variables:

• One for minimum

• One for maximum
We update both in the same loop.

Step-by-Step Explanation

1.Read n and array.

2.Initialize min = a[0], max = a[0].

3.Loop from i = 1 to n-1:

• If a[i] < min, update min.

• If a[i] > max, update max.

4.Return [min, max].

Concept Explanation

We keep two variables:

• One for minimum

• One for maximum
We update both in the same loop.

Step-by-Step Explanation

1.Read n and array.

2.Initialize min = a[0], max = a[0].

3.Loop from i = 1 to n-1:

• If a[i] < min, update min.

• If a[i] > max, update max.

4.Return [min, max].

Input / Output Format

Input Format
An integer n
Then n integers
Output Format
An array [min, max]
Constraints
• n ≥ 1

• Must use single loop

Examples

Input:
5 8 3 12 -4 7
Output:
[-4, 12]

Example Solution (Public)

Java
static int[] minMax(int[] a){int mn=a[0],mx=a[0];for(int i=1;i<a.length;i++){int x=a[i];if(x<mn) mn=x; if(x>mx) mx=x;}return new int[]{mn,mx};}

Official Solution Code

static int[] minMax(int[] a){int mn=a[0],mx=a[0];for(int i=1;i<a.length;i++){int x=a[i];if(x<mn) mn=x; if(x>mx) mx=x;}return new int[]{mn,mx};}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.