Torna alle sfide
Facile 0 risolte 0% di accettazione

Make an Array Nondecreasing

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

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

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

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

Output atteso:
long expected = 4;

Spiegazione

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

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

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

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

Output atteso:
long expected = 0;

Spiegazione

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

Come affrontarlo

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

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

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.