768. Max Chunks To Make Sorted II

Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

Example 1:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.

这道题不知道为什么是道hard。我素来对hard题有着深深的敬畏之心, 不过这道看了之后感觉这就是一个披着狼皮的羊, 过来滥竽充数的吧。这道就是sliding widing, two pointer两种方法搞一搞。

可能有一点比较难的地方,就是在于一定要从左边开始搞,或者从另外一边右边开始搞。
总而言之这种切块问题一定要从一端开始做。这是这题里面比较greedy的地方,可能这一点比较难吧。
不过这种也常见,比如995那道题。https://www.jianshu.com/p/4c4f56213cac ,也是一定要从左边开始。
995我那个帖子里面证明了为什么一定要从一端开始。
大概就是端点的元素只有一侧的元素可以合作,是自由度最小的。先满足它们。
下面帖下代码.

 public int maxChunksToSorted(int[] arr) {
        int[] helper = Arrays.copyOf(arr, arr.length);
        Arrays.sort(helper);
        Map minMaxIndexMap = new HashMap<>();
        int slow = 0, fast = 0;
        while (fast < helper.length) {
            while (fast + 1 < helper.length && helper[fast + 1] == helper[fast]) {
                fast++;
            }
            minMaxIndexMap.put(helper[fast], new int[]{slow, fast});
            slow = ++fast;
        }
        int count = 0;
        fast = 0;
        int max = 0;
        while (fast < arr.length) {
            int n = arr[fast];
            int[] indexes = minMaxIndexMap.get(n);
            int index = indexes[0];
            indexes[0]++;
            max = Math.max(max, index);
            if (max == fast) { //  这时可以切!
                count++;
            }
            fast++;
        }
        return count;
    }

你可能感兴趣的:(768. Max Chunks To Make Sorted II)