Skip to content

Commit e875524

Browse files
committed
row with max 1
1 parent 73812d9 commit e875524

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Diff for: DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
- [Spirally traversing a matrix](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1# "view question") - [Cpp Solution](./solutions/Spirally%20traversing%20a%20matrix.cpp)
4747
- [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/ "view question") - [Cpp Solution](./solutions/Search%20a%202D%20Matrix.cpp)
4848
- [Median in a row-wise sorted Matrix](https://practice.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1 "view question") - [Cpp Solution](./solutions/Median%20in%20a%20row-wise%20sorted%20Matrix.cpp)
49+
- [Row with max 1s](https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1# "view question") - [Cpp Solution](./solutions/Row%20with%20max%201s.cpp)
4950
- []( "view question") - [Cpp Solution](./solutions/.cpp)
5051

5152
### Strings

Diff for: DSA Crack Sheet/solutions/Row with max 1s.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Row with max 1s
3+
===============
4+
5+
Given a boolean 2D array of n x m dimensions where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's.
6+
7+
Example 1:
8+
Input:
9+
N = 4 , M = 4
10+
Arr[][] = {{0, 1, 1, 1},
11+
{0, 0, 1, 1},
12+
{1, 1, 1, 1},
13+
{0, 0, 0, 0}}
14+
Output: 2
15+
Explanation: Row 2 contains 4 1's (0-based
16+
indexing).
17+
18+
Example 2:
19+
Input:
20+
N = 2, M = 2
21+
Arr[][] = {{0, 0}, {1, 1}}
22+
Output: 1
23+
Explanation: Row 1 contains 2 1's (0-based
24+
indexing).
25+
26+
Your Task:
27+
You don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.
28+
29+
Expected Time Complexity: O(N+M)
30+
Expected Auxiliary Space: O(1)
31+
32+
Constraints:
33+
1 ≤ N, M ≤ 103
34+
0 ≤ Arr[i][j] ≤ 1
35+
*/
36+
37+
int rowWithMax1s(vector<vector<int>> arr, int R, int C)
38+
{
39+
int max_row_index = -1;
40+
int j = upper_bound(arr[0].begin(), arr[0].end(), 0) - arr[0].begin();
41+
if (j == 0)
42+
return 0;
43+
44+
for (int i = 1; i < R; i++)
45+
{
46+
while (j - 1 >= 0 && arr[i][j - 1] == 1)
47+
{
48+
j = j - 1;
49+
max_row_index = i;
50+
}
51+
}
52+
return max_row_index;
53+
}

0 commit comments

Comments
 (0)