Easy 0 solved 0% acceptance

Array Maximum

Find the largest value in a list.

What you'll learn

  • Find the largest value in one pass
  • Initialize the maximum with the first element
  • Work with negative numbers

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

Example 1
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.

Example 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.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.