Facile 0 résolus 0 % de réussite

Array Maximum

Find the largest value in a list.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

1 ≤ length ≤ 100,000

Exemples

Exemple 1
Entrée :
numbers = [3, 9, 2]

Sortie attendue :
expected = 9
Entrée :
std::vector<long long> numbers = {3, 9, 2};

Sortie attendue :
long long expected = 9;
Entrée :
long[] numbers = new long[] {3, 9, 2};

Sortie attendue :
long expected = 9;

Explication

9 is larger than 3 and 2.

Exemple 2
Entrée :
numbers = [-4, -1, -7]

Sortie attendue :
expected = -1
Entrée :
std::vector<long long> numbers = {-4, -1, -7};

Sortie attendue :
long long expected = -1;
Entrée :
long[] numbers = new long[] {-4, -1, -7};

Sortie attendue :
long expected = -1;

Explication

With only negative values, -1 is the largest.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Start with the first element as the best value so far.

Indice 2

Scan the list once and update the best value whenever you find a larger one.

Indice 3

Do not assume values are positive; negatives can still be the maximum.

Complexité attendue

O(n) time, O(1) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.