Untitled
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Solution { // Function to get maximum sum of beauties of two non-intersecting sub-grids public static int get_ans(int N, List<List<Integer>> A) { int maxSum = Integer.MIN_VALUE; // Transpose 2D List to 2D Array for easier manipulation int[][] grid = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { grid[i][j] = A.get(i).get(j); } } for (int size1 = 1; size1 <= N; size1++) { for (int r1 = 0; r1 + size1 <= N; r1++) { for (int c1 = 0; c1 + size1 <= N; c1++) { int beauty1 = calculateBeauty(grid, r1, c1, size1); for (int size2 = 1; size2 <= N; size2++) { for (int r2 = 0; r2 + size2 <= N; r2++) { for (int c2 = 0; c2 + size2 <= N; c2++) { if (areNonIntersecting(r1, c1, size1, r2, c2, size2)) { int beauty2 = calculateBeauty(grid, r2, c2, size2); maxSum = Math.max(maxSum, beauty1 + beauty2); } } } } } } } return maxSum; } private static int calculateBeauty(int[][] grid, int r, int c, int size) { int maxVal = Integer.MIN_VALUE; int minVal = Integer.MAX_VALUE; for (int i = r; i < r + size; i++) { for (int j = c; j < c + size; j++) { maxVal = Math.max(maxVal, grid[i][j]); minVal = Math.min(minVal, grid[i][j]); } } return maxVal - minVal; } private static boolean areNonIntersecting(int r1, int c1, int size1, int r2, int c2, int size2) { // Ensure that the two sub-grids do not overlap by checking rows and columns return (r1 + size1 <= r2 || r2 + size2 <= r1) && (c1 + size1 <= c2 || c2 + size2 <= c1); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int N = Integer.parseInt(scan.nextLine().trim()); List<List<Integer>> A = new ArrayList<>(N); for (int i = 0; i < N; i++) { A.add(Arrays.stream(scan.nextLine().trim().split(" ")) .map(Integer::parseInt) .collect(Collectors.toList())); } int result = get_ans(N, A); System.out.println(result); } }
Leave a Comment