|
| 1 | + |
| 2 | +//768. Max Chunks To Make Sorted II |
| 3 | + |
| 4 | +//You are given an integer array arr. |
| 5 | + |
| 6 | +//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. |
| 7 | + |
| 8 | +//Return the largest number of chunks we can make to sort the array. |
| 9 | + |
| 10 | + |
| 11 | +//Example 1: |
| 12 | + |
| 13 | +//Input: arr = [5,4,3,2,1] |
| 14 | +//Output: 1 |
| 15 | +//Explanation: |
| 16 | +//Splitting into two or more chunks will not return the required result. |
| 17 | +//For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. |
| 18 | + |
| 19 | +//Example 2: |
| 20 | + |
| 21 | +//Input: arr = [2,1,3,4,4] |
| 22 | +//Output: 4 |
| 23 | +//Explanation: |
| 24 | +//We can split into two chunks, such as [2, 1], [3, 4, 4]. |
| 25 | +//However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. |
| 26 | + |
| 27 | + |
| 28 | +//Constraints: |
| 29 | + |
| 30 | +//1 <= arr.length <= 2000 |
| 31 | +//0 <= arr[i] <= 108 |
| 32 | + |
| 33 | +import java.util.Scanner; |
| 34 | + |
| 35 | +public class Max_Chunks_To_Make_Sorted_II { |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + Scanner sc = new Scanner(System.in); |
| 39 | + |
| 40 | + System.out.println("Enter Number of element : "); |
| 41 | + int n = sc.nextInt(); |
| 42 | + |
| 43 | + int arr[] = new int[n]; |
| 44 | + System.out.println("Enter " + n + " values :"); |
| 45 | + for (int i = 0; i < n; i++) { |
| 46 | + arr[i] = sc.nextInt(); |
| 47 | + } |
| 48 | + int ans = maxChunksToSorted2(arr); |
| 49 | + |
| 50 | + System.out.println("Maximun chunk to sorts are : " + ans); |
| 51 | + } |
| 52 | + |
| 53 | + private static int maxChunksToSorted2(int[] arr) { |
| 54 | +// generate right minimum |
| 55 | + int[] rmin = new int[arr.length + 1]; |
| 56 | + |
| 57 | + rmin[arr.length] = Integer.MAX_VALUE; |
| 58 | + for (int i = arr.length - 1; i >= 0; i--) { |
| 59 | + rmin[i] = Math.min(rmin[i + 1], arr[i]); |
| 60 | + } |
| 61 | + |
| 62 | +// iterate on array and manage left maximum as well as count chunk |
| 63 | + int lmax = Integer.MIN_VALUE; |
| 64 | + int count = 0; |
| 65 | + for (int i = 0; i < arr.length; i++) { |
| 66 | + lmax = Math.max(lmax, arr[i]); |
| 67 | +// if the left max element is less than right minimum element than left partis one of the chunk so increment count |
| 68 | + if (lmax <= rmin[i + 1]) |
| 69 | + count++; |
| 70 | + } |
| 71 | + return count; |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments