| 1 | //TC -> (N-2)*(N-2)*(9log9 + 6log6) |
| 2 | |
| 3 | class Solution { |
| 4 | // this function will return remove the last column and add a new column example |
| 5 | // if matrix is [A,B,C,X] then the first 3*3 matrix(starting at [0,0] cell) would be [A,B,C] and second 3*3 matrix(starting at 0,1 cell) would be [B,C,X] |
| 6 | // [D,E,F,Y] [D,E,F] [E,F,Y] |
| 7 | // [G,H,I,Z] [G,H,I] [H,I,Z] |
| 8 | // so we can see that b/w these two matrix first column is removed and next column is added. |
| 9 | // so we can maintain a priority queue and store first 9 elements, |
| 10 | // Hence for every 3*3 matrix starting at the ith row and jth column ([i,j] cell and j>0) remove the (j-1)th column, add the (j+2)th column and find the maximum |
| 11 | // at every new row, reinitialize the queue. |
| 12 | public int findMax(int[][] grid, int startRow, int startCol, PriorityQueue<Integer> pq){ |
| 13 | //for every new row, init the queue and store 9 elements (3*3) |
| 14 | // TC -> O(9log9) [for inserting 1 element in pq, tc is logK, where k is number of element, our pq will always have 9 elements at max] |
| 15 | if(startCol==0){ |
| 16 | pq.clear(); |
| 17 | for(int i=startRow;i<startRow+3;i++){ |
| 18 | for(int j=startCol;j<startCol+3;j++){ |
| 19 | pq.offer(grid[i][j]); |
| 20 | } |
| 21 | } |
| 22 | }else{ |
| 23 | //TC -> 6log9 [remove -> 3log9 + insert 3log9] |
| 24 | //for same row, use sliding window to remove the (j-1)th column and add (j+2) column |
| 25 | for(int j=startRow;j<startRow+3;j++){ |
| 26 | pq.remove(grid[j][startCol-1]); |
| 27 | pq.offer(grid[j][startCol+2]); |
| 28 | } |
| 29 | } |
| 30 | return pq.peek(); |
| 31 | } |
| 32 | public int[][] largestLocal(int[][] grid) { |
| 33 | //priorityQueue to return the maximum values out of 9 values (3*3 matrix) |
| 34 | PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); |
| 35 | int rows=grid.length; |
| 36 | int cols=grid[0].length; |
| 37 | int result[][] = new int[rows-2][cols-2]; |
| 38 | //ietrate the starting cells of all possible 3*3 matirx |
| 39 | //TC-> (n-2 * n-2) |
| 40 | for(int i=0;i<rows-2;i++){ |
| 41 | for(int j=0;j<cols-2;j++){ |
| 42 | //update the queue and return the max element |
| 43 | result[i][j] = findMax(grid,i,j,pq); |
| 44 | } |
| 45 | } |
| 46 | return result; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | //Note-> this is slower than the brute force approach but it can be helpful in finding the sum of all 3*3 matrix, i.e instead of a pq, use a prefix sum. |
| 51 |
nothing calls this directly
no outgoing calls
no test coverage detected