Project Euler #11: Largest product in a grid

  • + 0 comments
    public static int largestProductGrid(int[][] grid) {
            int max = 0, product;
            for (int rows = 0; rows <= 19; rows++) {
                for (int columns = 0; columns <= 19; columns++) {
                    if (columns + 3 <= 19) {
                        product = grid[rows][columns] * grid[rows][columns + 1] * grid[rows][columns + 2] * grid[rows][columns + 3];
                        if (product > max) {
                            max = product;
                        }
                    }
                    if (rows + 3 <= 19) {
                        product = grid[rows][columns] * grid[rows + 1][columns] * grid[rows + 2][columns] * grid[rows + 3][columns];
                        if (product > max) {
                            max = product;
                        }
                    }
                    if (columns + 3 <= 19 && rows + 3 <= 19) {
                        product = grid[rows][columns] * grid[rows + 1][columns + 1] * grid[rows + 2][columns + 2] * grid[rows + 3][columns + 3];
                        if (product > max) {
                            max = product;
                        }
                    }
                    if (rows + 3 <= 19 && columns - 3 >= 0) {
                        product = grid[rows][columns] * grid[rows + 1][columns - 1] * grid[rows + 2][columns - 2] * grid[rows + 3][columns - 3];
                        if (product > max) {
                            max = product;
                        }
                    }
                }
            }
            return max;
        }