Skip to content

Commit 82642a5

Browse files
authored
Added task 768.
1 parent c897991 commit 82642a5

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package g0701_0800.s0768_max_chunks_to_make_sorted_ii;
2+
3+
// #Hard #Array #Sorting #Greedy #Stack #Monotonic_Stack
4+
5+
public class Solution {
6+
public int maxChunksToSorted(int[] arr) {
7+
int n = arr.length;
8+
int[] lmax = new int[n];
9+
int[] rmin = new int[n + 1];
10+
lmax[0] = arr[0];
11+
for (int i = 1; i < n; i++) {
12+
lmax[i] = Math.max(lmax[i - 1], arr[i]);
13+
}
14+
rmin[n] = Integer.MAX_VALUE;
15+
for (int i = n - 1; i >= 0; i--) {
16+
rmin[i] = Math.min(rmin[i + 1], arr[i]);
17+
}
18+
int chunks = 0;
19+
for (int i = 0; i < n; i++) {
20+
if (lmax[i] <= rmin[i + 1]) {
21+
chunks++;
22+
}
23+
}
24+
return chunks;
25+
}
26+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
768\. Max Chunks To Make Sorted II
2+
3+
Hard
4+
5+
You are given an integer array `arr`.
6+
7+
We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
8+
9+
Return _the largest number of chunks we can make to sort the array_.
10+
11+
**Example 1:**
12+
13+
**Input:** arr = [5,4,3,2,1]
14+
15+
**Output:** 1
16+
17+
**Explanation:**
18+
19+
Splitting into two or more chunks will not return the required result.
20+
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
21+
22+
**Example 2:**
23+
24+
**Input:** arr = [2,1,3,4,4]
25+
26+
**Output:** 4
27+
28+
**Explanation:**
29+
30+
We can split into two chunks, such as [2, 1], [3, 4, 4].
31+
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
32+
33+
**Constraints:**
34+
35+
* `1 <= arr.length <= 2000`
36+
* <code>0 <= arr[i] <= 10<sup>8</sup></code>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package g0701_0800.s0768_max_chunks_to_make_sorted_ii;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void maxChunksToSorted() {
11+
assertThat(new Solution().maxChunksToSorted(new int[] {5, 4, 3, 2, 1}), equalTo(1));
12+
}
13+
14+
@Test
15+
void maxChunksToSorted2() {
16+
assertThat(new Solution().maxChunksToSorted(new int[] {2, 1, 3, 4, 4}), equalTo(4));
17+
}
18+
}

0 commit comments

Comments
 (0)