Torna alle sfide
Facile 0 risolte 0% di accettazione

Second Largest Value

Find the second largest distinct value.

Cosa imparerai

  • Track the top two values in one pass
  • Ignore duplicates of the maximum
  • Handle lists without a second value

Problema

Mostra traduzione

Return the second largest distinct value in the list. Repeated values count once.

Implement second_largest(numbers).

Input

numbers: A list of non-negative integers.

Output

Return the second largest distinct value, or -1 if it doesn't exist.

Vincoli

0 ≤ length ≤ 100,000; 0 ≤ each value ≤ 10⁹

Esempi

Esempio 1
Input:
numbers = [4, 9, 7, 9]

Output atteso:
expected = 7
Input:
std::vector<long long> numbers = {4, 9, 7, 9};

Output atteso:
long long expected = 7;
Input:
long[] numbers = new long[] {4, 9, 7, 9};

Output atteso:
long expected = 7;

Spiegazione

Distinct values are 9, 7, 4; the second largest is 7.

Esempio 2
Input:
numbers = [5, 5]

Output atteso:
expected = -1
Input:
std::vector<long long> numbers = {5, 5};

Output atteso:
long long expected = -1;
Input:
long[] numbers = new long[] {5, 5};

Output atteso:
long expected = -1;

Spiegazione

Only one distinct value exists, so the answer is -1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

You need the largest and the next different value, not just the top two positions.

Suggerimento 2

Track two distinct maxima as you scan, updating them when a new value fits above or between them.

Suggerimento 3

If no second distinct value ever appears, return the special fallback value.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.