Todos los desafíos
Intermedio 0 resueltos 0% de aceptación

Maximum Path Sum in a Triangle

Find the largest sum on a path from the top of a number triangle to its bottom row.

Lo que aprenderás

  • Replace exponential search with dynamic programming
  • Combine results from the row below
  • Handle negative values and empty input

Problema

Ver traducción

A number triangle has one value on row 0, two on row 1, and so on. Start at the top and move down one row at a time, each time to the value directly below or the one below and to the right (from position i to i or i + 1). Find the path whose values add up to the most. Trying every path doubles the work each row; working upward from the bottom row keeps it quadratic.

Implement triangle_max_path_sum(triangle).

Input

triangle: The rows from top to bottom; row r has r + 1 values, which may be negative.

Output

Return the largest possible sum of a top-to-bottom path. An empty triangle returns 0.

Restricciones

0 ≤ rows ≤ 100; −1000 ≤ value ≤ 1000

Ejemplos

Ejemplo 1
Entrada:
triangle = [
    [4],
    [7, 2],
    [1, 9, 5],
    [6, 3, 8, 2]
]

Salida esperada:
expected = 28
Entrada:
std::vector<std::vector<long long>> triangle = {
    {4},
    {7, 2},
    {1, 9, 5},
    {6, 3, 8, 2}
};

Salida esperada:
long long expected = 28;
Entrada:
long[][] triangle = new long[][] {
    new long[] {4},
    new long[] {7, 2},
    new long[] {1, 9, 5},
    new long[] {6, 3, 8, 2}
};

Salida esperada:
long expected = 28;

Explicación

The best path is 4, 7, 9, 8 (position 0, 0, 1, 2), for 28.

Ejemplo 2
Entrada:
triangle = [
    [-3],
    [5, -8],
    [-1, 2, 9]
]

Salida esperada:
expected = 4
Entrada:
std::vector<std::vector<long long>> triangle = {
    {-3},
    {5, -8},
    {-1, 2, 9}
};

Salida esperada:
long long expected = 4;
Entrada:
long[][] triangle = new long[][] {
    new long[] {-3},
    new long[] {5, -8},
    new long[] {-1, 2, 9}
};

Salida esperada:
long expected = 4;

Explicación

With negatives, −3, 5, 2 gives 4 while −3, −8, 9 gives −2, so the answer is 4.

Cómo abordarlo

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

Pista 1

Start from the bottom row: the best path from a bottom cell is just its value.

Pista 2

The best path from a cell is its value plus the larger best of the two cells below it.

Pista 3

After processing every row upward, the top cell holds the answer.

Complejidad esperada

O(rows²) time, O(rows) extra space

Referencias

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

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

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