Largest Element in Array

Vimal Ganesh MVimal Ganesh M
1 min read

you want to find tallest boy in a class.

consider you are a P.T sir.

Approach 1:

So first, you tell all students to stand in a line from shortest to tallest. After the sorting is done, you look at the last boy — he’s clearly the tallest.

✅ Accurate.
❌ But it wastes time sorting everyone.
⏱️ Time taken: O(n log n) (if we think of sorting the array)

Approach 2:

This time, you try a better method.

  1. You look at the first boy and assume he’s the tallest.

  2. Then, one by one, you compare him with the next student.

  3. If someone is taller, you update your “tallest so far.”

  4. You continue until the last student.

🎯 At the end, you’ve found the tallest boy without sorting!

✅ Accurate.
✅ Efficient.
⏱️ Time taken: O(n) — only one pass!

class Solution {
    public static int largest(int[] arr) {
        // code here
        int height = arr[0];
        int n=arr.length;
        for(int i=1;i<n;i++){
            if (arr[i]>height) height=arr[i];
        }    
        return height;
    }
}
0
Subscribe to my newsletter

Read articles from Vimal Ganesh M directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vimal Ganesh M
Vimal Ganesh M