Largest Element in Array

Solved

Difficulty: Basic Accuracy: 100.00% Submissions: 1 Points: 1

You are given an array arr[] of integers. Find the largest value in it and return that value.

Examples:

Input: arr[] = [1, 8, 7, 56, 90]

Output: 90

Explanation: 90 is bigger than every other element.

Input: arr[] = [5, 5, 5, 5]

Output: 5

Explanation: All elements are equal, so the largest is 5.

Constraints:

  • 1 ≤ arr.size() ≤ 10^5
  • 0 ≤ arr[i] ≤ 10^9
Expected Complexities

Time Complexity: O(n)   Auxiliary Space: O(1)

Company Tags

InfosysOracle

Topic Tags

ArraysBasic

Walk through the array once and remember the biggest value seen so far. Start with the first element so you never compare against a made-up value like zero, which would be wrong for arrays of negative numbers.

class Solution:
    def largest(self, arr):
        best = arr[0]
        for x in arr:
            if x > best:
                best = x
        return best

One pass, so O(n) time and O(1) extra space.

Sign in to see your submissions.