Find maximum element

Find maximum element

Easy Java Arrays 22 views
Explanation Complexity

Problem Statement

Task: return the maximum value from a non-empty array.

Input Format

An integer n (size of array, non-empty)
Then n integers (array elements)

Output Format

The maximum value from the array.

Example

5
3 7 2 9 4
9

Constraints

• n ≥ 1

• Array is non-empty

• Integer values

Concept Explanation

To find the maximum value, we keep one variable and update it
whenever we see a bigger number while scanning the array once.

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Set max = arr[0].

4.Loop from index 1 to n-1.

5.If arr[i] > max, update max = arr[i].

6.After loop ends, max holds the largest value.

7.Print max.

Concept Explanation

To find the maximum value, we keep one variable and update it
whenever we see a bigger number while scanning the array once.

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Set max = arr[0].

4.Loop from index 1 to n-1.

5.If arr[i] > max, update max = arr[i].

6.After loop ends, max holds the largest value.

7.Print max.

Input / Output Format

Input Format
An integer n (size of array, non-empty)
Then n integers (array elements)
Output Format
The maximum value from the array.
Constraints
• n ≥ 1

• Array is non-empty

• Integer values

Examples

Input:
5 3 7 2 9 4
Output:
9

Example Solution (Public)

Java
static int maxElement(int[] a){int m=a[0];for(int i=1;i<a.length;i++) if(a[i]>m) m=a[i];return m;}

Official Solution Code

static int maxElement(int[] a){int m=a[0];for(int i=1;i<a.length;i++) if(a[i]>m) m=a[i];return m;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.