My approach for this question is that I made a landscape matrix (2-D) of size [max of x axis] [ max of y axis] ( x and y that are input by user). Then in the lanscape matrix, I have searched for rows and columns matching with the co-ordinates input by user, then I changed the values of those rows and columns to 1 from 0 which is default. In this way , the maximum area is largest sub-matrix inside landscape array having only 0 as element but I am not able to write code to find the largest sub-matrix
Not able to find the largest area
import java.util.Scanner; public class GrandTemple { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; int[] brr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); brr[i] = sc.nextInt(); } int a = max(arr); int b = max(brr); int[][]landscape=new int[a+1][b+1]; for(int i =0;i<landscape.length;i++) { for(int j =0;j<landscape[i].length;j++) { for(int k =0;k<arr.length;k++) { if(i==arr[k] || j==brr[k]) { landscape[i][j]=1; } } } } int[]count=new int[a*b]; } public static int max(int[] arr) { int max = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } }
@Syed-Siddiqui-2497215583854102,
You have to maximise the area obtained between the rivers. Since the intersection points of rivers are provided to you as input , you need to find the largest consecutive gap between the x coordinates and y coordinates.
This problem falls under the Greedy Algorithms section. A very similar problem ( practically the same ) is covered in the Greedy Algorithms tutorial video as well.
You need to implement a greedy algorithm for this problem.
Take the x coordinates input in an array , say X .
Take the y coordinates input in an array , say Y .
We need to find the maximum area. We can obtain it by finding the largest gap in the x coordinates and multiplying with the largest gap in the y coordinates.
So just do that , find the maximum gap between consecutive x coordinates in the X array and do the same for Y.
Multiply these maximum gaps and you will have your maximum area.
Hint : Sorting might help.
This is a pretty simple problem. All we need to do is just store all the X and Y coordinates and then sort them. Then we will calculate maximum ΔX and ΔY where ΔX = (Xi -X(i-1)) & ΔY = (Yi -Y(i-1)).
Then the area will be (ΔY-1)*(ΔX-1)
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.