C Online Compiler
Example: Efficient Pointer Max Ones Row in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Efficient Pointer Max Ones Row #include <stdio.h> #define ROWS 4 #define COLS 4 int main() { int matrix[ROWS][COLS] = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 1}, {0, 0, 0, 0} }; int maxOnesRow = -1; // Initialize to -1 to indicate no 1s found yet int i = 0; // Current row index, starts at the top int j = COLS - 1; // Current column index, starts at the rightmost column // Step 1: Traverse the matrix starting from the top-right corner // The loop continues as long as we are within matrix bounds while (i < ROWS && j >= 0) { if (matrix[i][j] == 1) { // Step 2: If the current element is '1' // This row (i) is a candidate for having max ones. // Since rows are sorted, all elements to the left (matrix[i][0] to matrix[i][j]) // are also 1s or 0s. The '1's extend at least up to column 'j'. // Update maxOnesRow and try to find '1's extending further left in this row maxOnesRow = i; // Mark current row as the best candidate found so far j--; // Move left to find if current row has even more 1s } else { // Step 3: If the current element is '0' // This entire column 'j' and anything to its right in the current row 'i' // are 0s. So, this row cannot have more 1s by moving left. // Move to the next row (downwards) to find a row with '1's. i++; } } printf("Row with maximum 1s: %d (0-indexed)\n", maxOnesRow); return 0; }
Output
Clear
ADVERTISEMENTS