Skip to content

Instantly share code, notes, and snippets.

@ClearNB
Created January 5, 2019 05:47
Show Gist options
  • Save ClearNB/234043edc3d8b0fd36e920421d01cf10 to your computer and use it in GitHub Desktop.
Save ClearNB/234043edc3d8b0fd36e920421d01cf10 to your computer and use it in GitHub Desktop.
Largest product in a grid (Java 8 ver) Sample by ClearNB
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int[][] grid = new int[20][20];
int[] x = {0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3};
int[] y = {1, 2, 3, 1, 2, 3, 0, 0, 0, -1, -2, -3};
try (Scanner in = new Scanner(System.in)) {
for(int grid_i = 0; grid_i < 20; grid_i++) {
for(int grid_j = 0; grid_j < 20; grid_j++){
grid[grid_i][grid_j] = in.nextInt();
}
}
}
long sum = 0;
long tempsum = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
for(int k = 0; k < 12; k++) {
if(k % 3 == 0) {
sum = Math.max(sum, tempsum);
tempsum = grid[i][j];
}
int xray = i + x[k];
int yray = j + y[k];
if(xray < 20 && xray >= 0 && yray >= 0 && yray < 20) {
tempsum *= grid[xray][yray];
}
}
sum = Math.max(sum, tempsum);
}
}
System.out.println(sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment