C++ Online Compiler
Example: OptimizedMaxOnesRow in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// OptimizedMaxOnesRow #include <iostream> #include <vector> using namespace std; int findRowWithMaxOnesOptimized(const vector<vector<int>>& matrix) { int numRows = matrix.size(); if (numRows == 0) return -1; int numCols = matrix[0].size(); if (numCols == 0) return -1; int maxRowIndex = -1; int j = numCols - 1; // Start from the top-right corner // Traverse rows for (int i = 0; i < numRows; ++i) { // While current element is 1 and we haven't gone out of bounds while (j >= 0 && matrix[i][j] == 1) { maxRowIndex = i; // This row has at least 'j' number of ones (numCols - j) // It's a candidate for max ones, so store its index. j--; // Move left to check for more ones in the current row } } return maxRowIndex; } int main() { // Step 1: Define the example matrix vector<vector<int>> matrix = { {0, 0, 1, 1}, {0, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 1, 1} }; // Step 2: Call the function to find the row with maximum ones int result = findRowWithMaxOnesOptimized(matrix); // Step 3: Print the result cout << "Optimized Two-Pointer Approach: Row with maximum 1s is at index " << result << endl; return 0; }
Output
Clear
ADVERTISEMENTS