Largest Product II

For each position i, j in a 2 dimension array, compute the product along the row and along the column. Each product should use 4 consecutive digits starting at i, j. Get the max for rows and max for columns.

9 2 4 6 1 7 5
6 2 4 5 9 2 7
9 4 0 1 7 4 8
1 0 5 6 5 1 2
7 5 9 7 7 4 6

function getMaxByRow(grid, row, col, numCount) {
  let max = 0
  let n = grid[row][col]
  let r = 0
  let c = 0
      
  for (let j = 1; j < numCount; j++) {
    n *= grid[row][col+j]
  }

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

  return { n: max, r, c }
}

function getMaxByCol(grid, row, col, numCount) {
  let max = 0
  let n = grid[row][col]
      
  for (let j = 1; j < numCount; j++) {
    n *= grid[row+j][col]
  }

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

  return { n: max, r, c }
}

function getMax(grid, numCount) {
  let max = 0
  let row = 0
  let col = 0

  for (let r = 0; r < grid.length -1 - numCount; r++) {
    let { n, r, c } = getMaxByRow(grid, r, 0, numCount)
      
    if (n > max) {
      max = n
      row = r
      col = c
    }
  }

  console.log(`max row is: ${max} ${row}, ${col}`)

  max = 0
  row = 0
  col = 0

  for (let c = 0; c < grid[].length -1 - numCount; c++) {
    let { n, r, c } = getMaxByCol(grid, 0, c, numCount)

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

  console.log(`max col is: ${max} ${row}, ${col}`)
}
Scroll to top