Problema
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.
Vincoli
1 ≤ length ≤ 100,000
Esempi
Input:
numbers = [3, 9, 2]
Output atteso:
expected = 9
Input:
std::vector<long long> numbers = {3, 9, 2};
Output atteso:
long long expected = 9;
Input:
long[] numbers = new long[] {3, 9, 2};
Output atteso:
long expected = 9;
Spiegazione
9 is larger than 3 and 2.
Input:
numbers = [-4, -1, -7]
Output atteso:
expected = -1
Input:
std::vector<long long> numbers = {-4, -1, -7};
Output atteso:
long long expected = -1;
Input:
long[] numbers = new long[] {-4, -1, -7};
Output atteso:
long expected = -1;
Spiegazione
With only negative values, -1 is the largest.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Start with the first element as the best value so far.
Suggerimento 2
Scan the list once and update the best value whenever you find a larger one.
Suggerimento 3
Do not assume values are positive; negatives can still be the maximum.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.