|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 769. Max Chunks To Make Sorted |
| 5 | +
|
| 6 | + Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. |
| 7 | + After concatenating them, the result equals the sorted array. |
| 8 | +
|
| 9 | + What is the most number of chunks we could have made? |
| 10 | +
|
| 11 | + Example 1: |
| 12 | +
|
| 13 | + Input: arr = [4,3,2,1,0] |
| 14 | + Output: 1 |
| 15 | + Explanation: |
| 16 | + Splitting into two or more chunks will not return the required result. |
| 17 | + For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted. |
| 18 | +
|
| 19 | + Example 2: |
| 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 | + Note: |
| 28 | +
|
| 29 | + arr will have length in range [1, 10]. |
| 30 | + arr[i] will be a permutation of [0, 1, ..., arr.length - 1]. |
| 31 | +
|
| 32 | + */ |
| 33 | +public class _769 { |
| 34 | + public static class Solution1 { |
| 35 | + /**credit: https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/113520/Java-solution-left-max-and-right-min.*/ |
| 36 | + public int maxChunksToSorted(int[] arr) { |
| 37 | + int len = arr.length; |
| 38 | + |
| 39 | + int[] maxOfLeft = new int[len]; |
| 40 | + maxOfLeft[0] = arr[0]; |
| 41 | + for (int i = 1; i < len; i++) { |
| 42 | + maxOfLeft[i] = Math.max(arr[i], maxOfLeft[i - 1]); |
| 43 | + } |
| 44 | + |
| 45 | + int[] minOfRight = new int[len]; |
| 46 | + minOfRight[len - 1] = arr[len - 1]; |
| 47 | + for (int i = len - 2; i >= 0; i--) { |
| 48 | + minOfRight[i] = Math.min(minOfRight[i + 1], arr[i]); |
| 49 | + } |
| 50 | + |
| 51 | + int result = 0; |
| 52 | + for (int i = 0; i < len - 1; i++) { |
| 53 | + if (maxOfLeft[i] <= minOfRight[i + 1]) { |
| 54 | + result++; |
| 55 | + } |
| 56 | + } |
| 57 | + return result + 1; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public static class Solution2 { |
| 62 | + /**credit: https://leetcode.com/articles/max-chunks-to-make-sorted-i/*/ |
| 63 | + public int maxChunksToSorted(int[] arr) { |
| 64 | + int ans = 0, max = 0; |
| 65 | + for (int i = 0; i < arr.length; ++i) { |
| 66 | + max = Math.max(max, arr[i]); |
| 67 | + if (max == i) ans++; |
| 68 | + } |
| 69 | + return ans; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments