ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Largest Product in a Grid

Find the largest product of k numbers in a straight line in a grid.

สิ่งที่คุณจะได้เรียนรู้

  • Walk a grid in four directions with step pairs
  • Check bounds before reading a run
  • Track a running maximum

โจทย์

ดูฉบับแปล

A run is k cells in a straight line: left to right along a row, top to bottom down a column, or along either diagonal. Multiply the numbers in a run and find the run with the largest product.

Implement largest_product_in_grid(grid, k).

Input

grid: A rectangular grid of numbers; every row has the same length.

k: The length of a run.

Output

Return the largest product over all runs of length k. If no run of length k fits in the grid in any direction, return 0.

เงื่อนไข

1 ≤ rows, columns ≤ 20; 0 ≤ grid[r][c] ≤ 99; 1 ≤ k ≤ 5

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
k = 2

ผลลัพธ์ที่คาดหวัง:
expected = 72
อินพุต:
std::vector<std::vector<long long>> grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
long long k = 2;

ผลลัพธ์ที่คาดหวัง:
long long expected = 72;
อินพุต:
long[][] grid = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7, 8, 9}
};
long k = 2;

ผลลัพธ์ที่คาดหวัง:
long expected = 72;

คำอธิบาย

The best run is 8 and 9 on the bottom row: 8 × 9 = 72. The diagonal 5, 9 only gives 45.

ตัวอย่างที่ 2
อินพุต:
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
k = 3

ผลลัพธ์ที่คาดหวัง:
expected = 504
อินพุต:
std::vector<std::vector<long long>> grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
long long k = 3;

ผลลัพธ์ที่คาดหวัง:
long long expected = 504;
อินพุต:
long[][] grid = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7, 8, 9}
};
long k = 3;

ผลลัพธ์ที่คาดหวัง:
long expected = 504;

คำอธิบาย

The bottom row gives 7 × 8 × 9 = 504, larger than the right column 3 × 6 × 9 = 162 or any diagonal.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Four directions are enough: right, down, down-right and down-left. The others repeat the same runs backwards.

คำใบ้ 2

From each start cell, check that the last cell of the run is still inside the grid.

คำใบ้ 3

Return 0 only when no run of length k fits at all.

ความซับซ้อนที่คาดหวัง

O(rows × cols × k) time, O(1) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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

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

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