मध्यम 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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

हर कोडर का सबसे अच्छा पास हुआ समाधान। तेज़, कम मेमोरी वाले और बेहतर रेटिंग वाले समाधान ऊपर रहते हैं।

अभी कोई पास हुआ समाधान नहीं है। इसे हल करें और पहला स्थान पाएँ।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।