Facile 3 risolte 100.0% di accettazione

Running Sum

Replace each value with the total so far.

Cosa imparerai

  • Compute totals so far
  • Build a new list of results
  • Learn the prefix sum idea

Problema

Mostra traduzione

Build a running sum: the value at position i is the sum of all numbers from position 0 through i.

Implement running_sum(numbers).

Input

numbers: The list of integers.

Output

Return the list of running totals.

Vincoli

0 ≤ length ≤ 100,000; totals fit in a 64-bit integer

Esempi

Esempio 1
Input:
numbers = [1, 2, 3, 4]

Output atteso:
expected = [1, 3, 6, 10]
Input:
std::vector<long long> numbers = {1, 2, 3, 4};

Output atteso:
std::vector<long long> expected = {1, 3, 6, 10};
Input:
long[] numbers = new long[] {1, 2, 3, 4};

Output atteso:
long[] expected = new long[] {1, 3, 6, 10};

Spiegazione

Totals so far: 1, 1+2=3, 3+3=6, 6+4=10.

Esempio 2
Input:
numbers = [5, -5, 5]

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

Output atteso:
std::vector<long long> expected = {5, 0, 5};
Input:
long[] numbers = new long[] {5, -5, 5};

Output atteso:
long[] expected = new long[] {5, 0, 5};

Spiegazione

Totals: 5, 0, 5.

Come affrontarlo

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

Suggerimento 1

Each output element depends on the total of all earlier elements and itself.

Suggerimento 2

Keep a cumulative total as you move through the list.

Suggerimento 3

The first position should simply reflect the first input value.

Complessità attesa

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

Riferimenti

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

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 LMLaura Mahlow Python 787 ms - 4/5 Vedi il codice
2 RCRiccardo Corti Python 852 ms - 4/5 Vedi il codice
3 GTGarlic The Destroyer Rust 1,550 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 3 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.