모든 챌린지
보통 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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.