Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int[] solution(int[][] matrix) {
- int rows = matrix.length;
- int cols = matrix[0].length;
- int[] result = new int[2];
- int minDifference = Integer.MAX_VALUE;
- for (int i = 0; i < rows - 1; i++) {
- for (int j = 0; j < cols - 1; j++) {
- int[] avgs = {
- average(matrix, 0, i, 0, j),
- average(matrix, 0, i, j + 1, cols - 1),
- average(matrix, i + 1, rows - 1, 0, j),
- average(matrix, i + 1, rows - 1, j + 1, cols - 1)
- };
- int minAvg = Integer.MAX_VALUE, maxAvg = Integer.MIN_VALUE;
- boolean isMinusOne = false;
- for (int avg : avgs) {
- if (avg != -1) {
- minAvg = Math.min(minAvg, avg);
- maxAvg = Math.max(maxAvg, avg);
- } else if (avg == -1) {
- isMinusOne = true;
- break;
- }
- }
- if (isMinusOne) continue;
- if (minAvg != Integer.MAX_VALUE && maxAvg != Integer.MIN_VALUE) {
- if (maxAvg - minAvg <= minDifference) {
- minDifference = maxAvg - minAvg;
- result[0] = i;
- result[1] = j;
- }
- }
- }
- }
- return result;
- }
- public static int average(int[][] matrix, int r1, int r2, int c1, int c2) {
- int sum = 0;
- int count = 0;
- for (int i = r1; i <= r2; i++) {
- for (int j = c1; j <= c2; j++) {
- if (matrix[i][j] >= 0) {
- sum += matrix[i][j];
- count++;
- }
- }
- }
- return count == 0 ? -1 : sum / count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement