Skip to content

Commit d13aaad

Browse files
authored
Create Max_Chunks_To_Make_Sorted.java
1 parent 27ab34a commit d13aaad

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//769. Max Chunks To Make Sorted
2+
3+
//You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
4+
5+
//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.
6+
7+
//Return the largest number of chunks we can make to sort the array.
8+
9+
//Example 1:
10+
11+
//Input: arr = [4,3,2,1,0]
12+
//Output: 1
13+
//Explanation:
14+
//Splitting into two or more chunks will not return the required result.
15+
//For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
16+
17+
//Example 2:
18+
19+
//Input: arr = [1,0,2,3,4]
20+
//Output: 4
21+
//Explanation:
22+
//We can split into two chunks, such as [1, 0], [2, 3, 4].
23+
//However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
24+
25+
//Constraints:
26+
27+
//n == arr.length
28+
//1 <= n <= 10
29+
//0 <= arr[i] < n
30+
//All the elements of arr are unique.
31+
32+
import java.util.Scanner;
33+
34+
public class Max_Chunks_To_Make_Sorted {
35+
36+
public static void main(String[] args) {
37+
Scanner sc = new Scanner(System.in);
38+
39+
System.out.println("Enter Number of element : ");
40+
int n = sc.nextInt();
41+
42+
int arr[] = new int[n];
43+
System.out.println("Enter " + n + " values :");
44+
for (int i = 0; i < n; i++) {
45+
arr[i] = sc.nextInt();
46+
}
47+
int ans = maxChunksToSorted(arr);
48+
49+
System.out.println("Maximun chunk to sorts are : " + ans);
50+
51+
}
52+
53+
private static int maxChunksToSorted(int[] arr) {
54+
int max = 0;
55+
int count = 0;
56+
//compair the array index and its value.
57+
//reach the maximum of the arry element
58+
for (int i = 0; i < arr.length; i++) {
59+
max = Math.max(arr[i], max);
60+
//if the index and max count are same so there is one chunk so increment in count
61+
if (i == max) {
62+
count++;
63+
}
64+
}
65+
return count;
66+
}
67+
68+
}

0 commit comments

Comments
 (0)