すべてのチャレンジ
中級 0件解決済み 正答率0%

Maximum Path Sum in a Triangle

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

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

例

例 1
入力:
triangle = [
    [4],
    [7, 2],
    [1, 9, 5],
    [6, 3, 8, 2]
]

期待される出力:
expected = 28
入力:
std::vector<std::vector<long long>> triangle = {
    {4},
    {7, 2},
    {1, 9, 5},
    {6, 3, 8, 2}
};

期待される出力:
long long expected = 28;
入力:
long[][] triangle = new long[][] {
    new long[] {4},
    new long[] {7, 2},
    new long[] {1, 9, 5},
    new long[] {6, 3, 8, 2}
};

期待される出力:
long expected = 28;

解説

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

例 2
入力:
triangle = [
    [-3],
    [5, -8],
    [-1, 2, 9]
]

期待される出力:
expected = 4
入力:
std::vector<std::vector<long long>> triangle = {
    {-3},
    {5, -8},
    {-1, 2, 9}
};

期待される出力:
long long expected = 4;
入力:
long[][] triangle = new long[][] {
    new long[] {-3},
    new long[] {5, -8},
    new long[] {-1, 2, 9}
};

期待される出力:
long expected = 4;

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。