-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Row_with_max_1s.cpp
87 lines (72 loc) · 1.78 KB
/
Row_with_max_1s.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* Row with max 1s = Here given a boolean 2D array where each row is sorted, so here find which first row contain maximum number of 1's.
ALGORITHM:
* 1st take value row and col by user input where row = No of row, col = No of column and then we create a 2D vector (matrix)
* Then we created a function find_Max1s
* find_Max1s = 1. 1st initialize i, j=col-1, index = -1
2. for i=0 to row
while j>=0
if a[i][j]==1
index=i
j--
else
break
3. return index
*/
#include <bits/stdc++.h>
using namespace std;
// finding row with max 1s
int find_Max1s(vector<vector<int>> a, int row, int col)
{
int i, j = col - 1, index = -1;
for (i = 0; i < row; i++)
{
while (j >= 0)
{
//when a[i][j]==1 then j decrement
if (a[i][j] == 1)
{
//here store the row index i
index = i;
j--;
}
else
break;
}
}
return index;
}
int main()
{
int row, col;
cout << "No of row : ";
cin >> row;
cout << "No of column : ";
cin >> col;
vector<vector<int>> a(row, vector<int>(col));
cout << "Taking the matrix : " << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> a[i][j];
}
}
int ans = find_Max1s(a, row, col);
cout << "Output : ";
cout << ans << endl;
return 0;
}
/*
INPUT:
No of row : 5
No of column : 5
Taking the matrix :
0 0 0 1 1
1 1 1 0 1
1 1 0 0 0
0 0 0 0 0
1 1 1 0 0
Output : 1
Time Complexity : O(row x col)
Space Complexity : O(1)
*/