#### Java / Programs

# Write a Java program to count negative numbers in a 2-dimensional array which is sorted row and column wise. (Amazon interview question)

public class CountNegativeNumbers { /* * Amazon interview question */ public static void main(String[] args) { int[][] matrix = new int[][] { { -3, -2, -1, 0 }, { -2, -1, 0, 1 }, { -1, 0, 1, 2 }, { -1, 1, 2, 3 } }; int count = 0; int k = matrix[0].length - 1; for (int i = 0; i < matrix.length; i++) { for (int j = k; j >= 0; j--) { if (matrix[i][j] < 0) { count = count + j + 1; k = j; break; } } } System.out.println("Total negative nos: " + count); } }

More Related questions...