ปานกลาง 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก