Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Musíme vypočítať súčiny všetkých štvoríc vo všetkých smeroch a určiť, ktorá štvorica má najvyšší súčin.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
import java.util.Scanner; public class LargestProductGrid { private static final int N = 20; private static final int ADJACENT = 4; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[][] visited = new int[N][N]; int[][] matrix = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { matrix[i][j] = scanner.nextInt(); } } System.out.println(max(matrix, visited)); scanner.close(); } private static long max(int[][] matrix, int[][] visited) { long max = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { long product = productToRight(matrix, i, j); if (product > max) { max = product; } product = productToDown(matrix, i, j); if (product > max) { max = product; } product = productToDiagRight(matrix, i, j); if (product > max) { max = product; } product = productToDiagLeft(matrix, i, j); if (product > max) { max = product; } } } return max; } private static long productToRight(int[][] matrix, int i, int j) { long product = 1; if (j <= N - ADJACENT) { for (int r = j; r < j + ADJACENT; r++) { product *= matrix[i][r]; } } return product; } private static long productToDown(int[][] matrix, int i, int j) { long product = 1; if (i <= N - ADJACENT) { for (int r = i; r < i + ADJACENT; r++) { product *= matrix[r][j]; } } return product; } private static long productToDiagRight(int[][] matrix, int i, int j) { long product = 1; int s = j; if (i <= N - ADJACENT && j <= N - ADJACENT) { for (int r = i; r < i + ADJACENT; r++) { product *= matrix[r][s++]; } } return product; } private static long productToDiagLeft(int[][] matrix, int i, int j) { long product = 1; if (i <= N - ADJACENT && j >= ADJACENT - 1) { for (int r = i; r < i + ADJACENT; r++) { product *= matrix[r][j--]; } } return product; } } |