Volver a los desafíos
Fácil 0 resueltos 0% de aceptación

Make an Array Nondecreasing

Find the fewest increments needed so each value is at least the previous one.

Lo que aprenderás

  • Fix each value relative to the previous one
  • Count the total moves needed
  • See why a greedy choice is optimal

Problema

Ver traducción

One move increases one array value by 1. Make the array nondecreasing: each value must be greater than or equal to the one immediately before it. You may not decrease values or reorder them.

Implement increasing_array(numbers).

Input

numbers: The values in their original order.

Output

Return the minimum total number of unit increments.

Restricciones

1 ≤ length ≤ 200,000. Each value is between 1 and 1,000,000,000. Use a signed 64-bit result.

Ejemplos

Ejemplo 1
Entrada:
numbers = [4, 1, 3]

Salida esperada:
expected = 4
Entrada:
std::vector<long long> numbers = {4, 1, 3};

Salida esperada:
long long expected = 4;
Entrada:
long[] numbers = new long[] {4, 1, 3};

Salida esperada:
long expected = 4;

Explicación

Raise 1 to 4 using three moves and 3 to 4 using one move. The result [4, 4, 4] uses four moves.

Ejemplo 2
Entrada:
numbers = [1, 2, 2, 5]

Salida esperada:
expected = 0
Entrada:
std::vector<long long> numbers = {1, 2, 2, 5};

Salida esperada:
long long expected = 0;
Entrada:
long[] numbers = new long[] {1, 2, 2, 5};

Salida esperada:
long expected = 0;

Explicación

Every value is already at least the preceding value; equal neighbors are allowed.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Scan from left to right, because each value only depends on the previous one.

Pista 2

Whenever a value is too small, raise it just enough to match the running minimum allowed value.

Pista 3

Track the total increments carefully, since earlier increases affect later comparisons.

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.