Skip to content

Commit db9ea22

Browse files
committedJan 21, 2018
leetcode 769
1 parent 4260de9 commit db9ea22

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
 
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
Time spent : 10 min(See a little hint)
2+
3+
GIVEN: an array that is a permutation of [1,2,3,….,arr.length - 1]
4+
5+
RETURNS: the maximum chunks to make the array sorted
6+
7+
Note: we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.
8+
9+
EXAMPLES:
10+
11+
```
12+
Input: arr = [4,3,2,1,0]
13+
Output: 1
14+
Explanation:
15+
Splitting into two or more chunks will not return the required result.
16+
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
17+
18+
```
19+
20+
```
21+
Input: arr = [1,0,2,3,4]
22+
Output: 4
23+
Explanation:
24+
We can split into two chunks, such as [1, 0], [2, 3, 4].
25+
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
26+
```
27+
28+
DESIGN STRATEGY:
29+
30+
For the array like 6,5,8,7,4,3,2,0,1 we can see that once 8 is at index 2, there is no way to make several chunks of next number, and 6,5 are all larger than 4,3,2,0,1. So what we need to do is find the current maximum number, and compare the number with the i. If the number == i and it is the max one now, we can make it a chunk.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public int maxChunksToSorted(int[] arr) {
3+
int large = 0;
4+
int count = 0;
5+
for (int i = 0; i < arr.length; i++) {
6+
large = Math.max(large, arr[i]);
7+
if (i == large) {
8+
count++;
9+
}
10+
}
11+
return count;
12+
}
13+
}

0 commit comments

Comments
 (0)
Please sign in to comment.