Skip to content

Commit c1f96c4

Browse files
Create max_chunks_to_make_sorted_ii.cpp
1 parent 2528a9b commit c1f96c4

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

max_chunks_to_make_sorted_ii.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int maxChunksToSorted(vector<int>& arr) {
4+
5+
/*
6+
//if we have all elements towards left less than all elements towards right, then we have discovered a chunk
7+
//keep track of right min using rightMinArray
8+
//iterate over the actual array and calculate left max
9+
*/
10+
11+
int N = arr.size();
12+
vector<int> trackRightMin(N);
13+
int result = 0, max_ = 0;
14+
15+
for(int i=N-2; i>=0; --i)
16+
trackRightMin[i] = min(arr[i+1], arr[i]);
17+
18+
for(int i=0; i<N-1; ++i) {
19+
max_ = max(max_, arr[i]);
20+
if(max_ <= trackRightMin[i+1]) ++result;
21+
}
22+
return result+1;
23+
}
24+
};

0 commit comments

Comments
 (0)