You have a matrix consisting of rows and columns. Let be the maximum element of the matrix and be the smallest element of the matrix. If any element whose value is equal to or are called unsafe elements and they disfigure the complete row and column of the matrix. More formally, if any element is equal to or and contains cell number , that is, or are unsafe so that they also disfigure all the cells that have row or column and also are unsafe.
Your task is to find the number of safe elements.
Example:
Input:3 3 8 8 3 6 2 4 12 1 2Output:2
Approach
Java
package com.java;import java.util.HashSet;public class UnsafeElemINMatrix {public static void main(String[] args) {int r = 3;int c = 3;int min = 999999999;int max = 0;int[][] arr = { { 8, 8, 3 }, { 6, 2, 4 }, { 12, 1, 2 } };for (int i = 0; i < r; i++) {for (int j = 0; j < c; j++) {int val = arr[i][j];arr[i][j] = val;if (val > max) {max = val;}if (val < min) {min = val;}}}int rows = 0;HashSet<Integer> columns = new HashSet<Integer>();for (int i = 0; i < r; i++) {boolean pass = false;for (int j = 0; j < c; j++) {int val = arr[i][j];if (val == max || val == min) {if (!columns.contains(val)) {columns.add(val);}pass = true;}}if (pass) {rows++;}}System.out.println((r - rows) * (c - columns.size()));}}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Spring Boot Interview Questions Set 1
Spring Boot Interview Questions Set 2
No comments:
Post a Comment