Help the world stop coronavirus! Stay home!

Prev Next

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);

	}

}

❤Cash Back At Stores you Love !!!❤

Earn your $10 reward when you make your first purchase through Ebates by signing up with clicking below button.

Ebates Coupons and Cash Back

More Related questions...

Show more question and Answers...

JVM

Comments & Discussions