LeetCode 768. Max Chunks To Make Sorted II

原题链接在这里: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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11367324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值