C++ Online Compiler
Example: NaiveMaxOnesRow in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// NaiveMaxOnesRow #include <iostream> #include <vector> #include <algorithm> // Required for std::max using namespace std; int findRowWithMaxOnesNaive(const vector<vector<int>>& matrix) { int numRows = matrix.size(); if (numRows == 0) return -1; // Handle empty matrix int numCols = matrix[0].size(); if (numCols == 0) return -1; // Handle empty rows int maxOnes = -1; int maxRowIndex = -1; // Iterate through each row for (int i = 0; i < numRows; ++i) { int currentOnes = 0; // Iterate through each element in the current row for (int j = 0; j < numCols; ++j) { if (matrix[i][j] == 1) { currentOnes++; } } // Update if current row has more ones if (currentOnes > maxOnes) { maxOnes = currentOnes; maxRowIndex = i; } } 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 = findRowWithMaxOnesNaive(matrix); // Step 3: Print the result cout << "Naive Approach: Row with maximum 1s is at index " << result << endl; return 0; }
Output
Clear
ADVERTISEMENTS