Todos os desafios
Médio 0 resolvidos 0% de aceitação

Largest Product in a Grid

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

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

Exemplos

Exemplo 1
Entrada:
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
k = 2

Saída esperada:
expected = 72
Entrada:
std::vector<std::vector<long long>> grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
long long k = 2;

Saída esperada:
long long expected = 72;
Entrada:
long[][] grid = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7, 8, 9}
};
long k = 2;

Saída esperada:
long expected = 72;

Explicação

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

Exemplo 2
Entrada:
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
k = 3

Saída esperada:
expected = 504
Entrada:
std::vector<std::vector<long long>> grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
long long k = 3;

Saída esperada:
long long expected = 504;
Entrada:
long[][] grid = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7, 8, 9}
};
long k = 3;

Saída esperada:
long expected = 504;

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

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

Dica 2

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

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

Ainda não há soluções aprovadas. Resolva e fique com o primeiro lugar.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.