You are given an array arr[] of integers. Find the largest value in it and return that value.
Largest Element in Array
SolvedExamples:
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^50 ≤ arr[i] ≤ 10^9
Expected Complexities
Time Complexity: O(n) Auxiliary Space: O(1)
Company Tags
Topic Tags
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.