当前位置 : 主页 > 网页制作 > HTTP/TCP >

LeetCode 768. Max Chunks To Make Sorted II

来源:互联网 收集:自由互联 发布时间:2021-06-16
原题链接在这里:https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ 题目: This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array coul

原题链接在这里:https://leetcode.com/problems/max-chunks-to-make-sorted-ii/

题目:

This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.


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.

Example 2:

Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

Note:

  • arr will have length in range [1, 2000].
  • arr[i] will be an integer in range [0, 10**8].

题解:

We want to find the lines where all the values on line‘s left are smaller or equal to all the values on line‘s right.

Once we have the count of such lines, the chunks number is lines count + 1.

Then how to find such lines. We could track maximum from left and minimum from right and left maximimum <= right minimum, then there is such a line.

Time Complexity: O(n). n = arr.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int maxChunksToSorted(int[] arr) {
 3         int n = arr.length;
 4         int [] leftMax = new int[n];
 5         int [] rightMin = new int[n];
 6         int max = Integer.MIN_VALUE;
 7         for(int i = 0; i<n; i++){
 8             max = Math.max(max, arr[i]);
 9             leftMax[i] = max;
10         }
11         
12         int min = Integer.MAX_VALUE;
13         for(int i = n-1; i>=0; i--){
14             min = Math.min(min, arr[i]);
15             rightMin[i] = min;
16         }
17         
18         int res = 0;
19         for(int i = 0; i<n-1; i++){
20             if(leftMax[i]<=rightMin[i+1]){
21                 res++;
22             }
23         }
24         
25         return res + 1;
26     }
27 }
网友评论