Largest Product II

You are given a 2 dimensional array. Compute products of length n consecutive digits along the rows and along the columns. Find the largest product in all rows and the largest product in all columns.

For the 2 dimensional array below, where n = 2, the result is:

max row is: 81, starting index 3, 5
max col is: 72, starting index 2, 6

 [1, 2, 4, 6, 1, 7, 5] 
[1, 2, 4, 5, 9, 2, 7]
[9, 4, 0, 1, 7, 4, 8]
[1, 9, 5, 6, 5, 9, 9]
[7, 5, 9, 7, 7, 4, 6]
let grid = [
  [1, 2, 4, 6, 1, 7, 5],
  [1, 2, 4, 5, 9, 2, 7],
  [9, 4, 0, 1, 7, 4, 8],
  [1, 9, 5, 6, 5, 9, 9],
  [7, 5, 9, 7, 7, 4, 6]
]

let numCount = 3

function getMaxByRow(grid, row, col, numCount) {
  let max = 0
  let r = 0
  let c = 0
  let product = grid[row][col]

  for (var j = 1; j < numCount; j++) {
    product *= grid[row][col + j]
  }

  if (product > max) {
    max = product
    r = row
    c = col
  }

  return { max, r, c }
}

function getMaxByCol(grid, row, col, numCount) {
  let max = 0
  let r = 0
  let c = 0
  let product = grid[row][col]

  for (let j = 1; j < numCount; j += 1) {
    product *= grid[row + j][col]
  }

  if (product > max) {
    max = product
    r = row
    c = col
  }

  return { max, r, c }
}

function getMax(grid, numCount) {
  let maxRow = 0
  let maxRowRow = 0
  let maxRowCol = 0
  let maxCol = 0
  let maxColRow = 0
  let maxColCol = 0

  let numRows = grid.length
  let numCols = grid[0].length

  let rowsToIterate = (numRows + 1 - numCount)
  let colsToIterate = (numCols + 1 - numCount)

  for (let row = 0; row < numRows; row++) {
    for (let col = 0; col < numCols; col++) {

      if (row < rowsToIterate) {
        let { max, r, c } = getMaxByCol(grid, row, col, numCount)

        if (max > maxCol) {
          maxCol = max
          maxColRow = r
          maxColCol = c
        }
      }

      if (col < colsToIterate) {
        let { max, r, c } = getMaxByRow(grid, row, col, numCount)

        if (max > maxRow) {
          maxRow = max
          maxRowRow = r
          maxRowCol = c
        }
      }
    }
  }

  console.log(max row is: ${maxRow} ${maxRowRow}, ${maxRowCol})
  console.log(max col is: ${maxCol} ${maxColRow}, ${maxColCol})
}

getMax(grid, numCount)

 

Scroll to top