Problem
Return the largest value in the list by checking each element once.
Implement array_maximum(numbers).
Input
numbers: A non-empty list of integers.
Output
Return the maximum.
Constraints
1 ≤ length ≤ 100,000
Examples
Input:
numbers = [3, 9, 2]
Expected output:
expected = 9
Input:
std::vector<long long> numbers = {3, 9, 2};
Expected output:
long long expected = 9;
Input:
long[] numbers = new long[] {3, 9, 2};
Expected output:
long expected = 9;
Explanation
9 is larger than 3 and 2.
Input:
numbers = [-4, -1, -7]
Expected output:
expected = -1
Input:
std::vector<long long> numbers = {-4, -1, -7};
Expected output:
long long expected = -1;
Input:
long[] numbers = new long[] {-4, -1, -7};
Expected output:
long expected = -1;
Explanation
With only negative values, -1 is the largest.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
Start with the first element as the best value so far.
Hint 2
Scan the list once and update the best value whenever you find a larger one.
Hint 3
Do not assume values are positive; negatives can still be the maximum.
Expected complexity
O(n) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.