Max Chunks To Make Sorted LT769

时间:2021-08-20 00:07:51

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.  After concatenating them, the result equals the sorted array.

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

Example 1:

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

Example 2:

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

Note:

  • arr will have length in range [1, 10].
  • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].


1. Iterate the array, if all the elements on the left are smaller than the elements on the left, there is a new chunk. The first solution use two arrays, leftMax[i] to record the max element ending at i and starting from 0, rightMin[i] to record element starting at i and ending at 0.

Time complexity: O(n)

Space complexity: O(n)

class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr == null) return 1; int sz = arr.length;
int[] leftMax = new int[sz];
int[] rightMin = new int[sz]; leftMax[0] = arr[0];
for(int i = 1; i < sz; ++i) {
leftMax[i] = Math.max(leftMax[i-1], arr[i]);
} rightMin[sz-1] = arr[sz-1];
for(int i = sz-2; i >= 0; --i) {
rightMin[i] = Math.min(rightMin[i+1], arr[i]);
} int count = 1;
for(int i = 0; i < sz-1; ++i) {
if(leftMax[i] < rightMin[i+1] ) ++count;
} return count;
}
}

1a. Since we iterate either from left to right or right to left, we do not need two arrays to keep all the previous record and can use one varible to record the max element from the left so far, as long as the max element is smaller than the min element on the right, there is a new chunk

class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr == null) return 1; int sz = arr.length;
int[] rightMin = new int[sz];
rightMin[sz-1] = arr[sz-1];
for(int i = sz-2; i >= 0; --i) {
rightMin[i] = Math.min(rightMin[i+1], arr[i]);
} int max = arr[0];
int count = 1;
for(int i = 0; i < sz-1; ++i) {
max = Math.max(max, arr[i]);
if(max < rightMin[i+1]) ++count;
} return count;
}
}

1b. Iterate from right to left:

class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr == null) return 1; int sz = arr.length;
int[] leftMax = new int[sz];
leftMax[0] = arr[0];
for(int i = 1; i < sz; ++i) {
leftMax[i] = Math.max(leftMax[i-1], arr[i]);
} int rightMin = arr[sz-1];
int count = 1;
for(int i = sz-1; i >= 1; --i) {
rightMin = Math.min(rightMin, arr[i]);
if(leftMax[i-1] < rightMin) {
++count;
}
}
return count;
}
}

2. Since arr[i] will be a permutation of [0, 1, ..., arr.length - 1], each element is unique and after sorted, arr[i] = i, the elements on the left will be smaller than the elemnts on the right, as long as the max element at index i is arr[i].

Time complexity: O(n)

Space complexity: O(1)

class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr == null) return 1; int maxSoFar = arr[0];
int count = 0;
for(int i = 0; i < arr.length; ++i) {
maxSoFar = Math.max(maxSoFar, arr[i]);
if(maxSoFar == i) ++count;
} return count;
}
}

2a Another slightly optimisation to terminate the loop early if the max element arr[arr.length-1] is found

class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr == null) return 1; int maxSoFar = arr[0];
int count = 0;
for(int i = 0; i < arr.length; ++i) {
maxSoFar = Math.max(maxSoFar, arr[i]);
if(maxSoFar == arr.length-1) return count+1;
if(maxSoFar == i) ++count;
} return count;
}
}

3. Another way to think, if we consider each chunk, as a range [min, max] ended at max, if the next element is smaller than the previous max, we need to merge the range by poping up the max element of chunks which max element is bigger, we need to include the new element in the poped up chunks, otherwise, push the new max element. The number of elements on the stack means the number of chunks.

[4, 3, 2, 1, 0] -> [4] for 4 -> [4] for 3 -> [4] for 2 -> [4] for 1 -> [0]

[1, 0, 2, 3, 4] -> [1] -> [1] -> [1, 2] -> [1, 2, 3] -> [1, 2, 3, 4]

[1, 2, 0, 3] -> [1] -> [1, 2] -> [2] -> [2, 3]

Time complexity: O(n)

Space complexity: O(n)

class Solution {
public int maxChunksToSorted(int[] arr) {
Deque<Integer> maxStack = new LinkedList<Integer>(); for(int num: arr) {
if(maxStack.isEmpty() || num > maxStack.peek()) {
maxStack.push(num);
}
else {
int max = maxStack.peek();
while(!maxStack.isEmpty() && num < maxStack.peek()) {
maxStack.pop();
}
maxStack.push(max);
}
} return maxStack.size();
}
}

3a It can be observed from the code that we always push the current max as where the range ends.

public class Solution {

    public int maxChunksToSorted(int[] arr) {
Deque<Integer> maxStack = new LinkedList<Integer>(); for(int num: arr) {
int currMax = maxStack.isEmpty()? num: Math.max(num, maxStack.peek()); while(!maxStack.isEmpty() && num < maxStack.peek()) {
maxStack.pop();
} maxStack.push(currMax);
} return maxStack.size();
}
}

4. Another way is to caculate the distance between the current index with the expected sorted index, if the sum is 0, the whole chunk could be a sorted array.

Time complexity: O(n)

Space complexity: O(1)

public class Solution {

    public int maxChunksToSorted(int[] arr) {

        int count = 0, sum = 0;
for(int i = 0; i < arr.length; ++i) {
sum += arr[i] - i;
if(sum == 0) ++count;
}
return count;
} }

Max Chunks To Make Sorted LT769的更多相关文章

  1. &lbrack;LeetCode&rsqb; Max Chunks To Make Sorted II 可排序的最大块数之二

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given ...

  2. &lbrack;LeetCode&rsqb; Max Chunks To Make Sorted 可排序的最大块数

    Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into som ...

  3. &lbrack;Swift&rsqb;LeetCode768&period; 最多能完成排序的块 II &vert; Max Chunks To Make Sorted II

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given ...

  4. &lbrack;leetcode&rsqb;Weekly Contest 68 (767&period; Reorganize String&amp&semi;&amp&semi;769&period; Max Chunks To Make Sorted&amp&semi;&amp&semi;768&period; Max Chunks To Make Sorted II)

    766. Toeplitz Matrix 第一题不说,贼麻瓜,好久没以比赛的状态写题,这个题浪费了快40分钟,我真是...... 767. Reorganize String 就是给你一个字符串,能不 ...

  5. LeetCode - 768&period; Max Chunks To Make Sorted II

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given ...

  6. 最多的划分来使数组有序 Max Chunks To Make Sorted

    2018-12-01 11:05:46 一.Max Chunks To Make Sorted 问题描述: 问题求解: 由于没有重复,所以直观的来看对于每个遇到数,其能够被划分出来的前提是其前面已经有 ...

  7. Max Chunks To Make Sorted II LT768

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given ...

  8. 768&period; Max Chunks To Make Sorted II

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given ...

  9. &lbrack;LeetCode&rsqb; 769&period; Max Chunks To Make Sorted 可排序的最大块数

    Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into som ...

随机推荐

  1. 美团HD&lpar;4&rpar;-二级联动效果

    DJNavDropView.m #import "DJNavDropView.h" #import "DJCategory.h" #import "D ...

  2. Codeforces 55D Beautiful Number (数位统计)

    把数位dp写成记忆化搜索的形式,方法很赞,代码量少了很多. 下面为转载内容:  a positive integer number is beautiful if and only if it is  ...

  3. Oracle数据 行转列

    记录一段行转列SQL代码: select cs.standard_id,cs.area_code,cs.exu_dept, regexp_substr(exu_dept, , level) as de ...

  4. 使用PHP和HTML5 FormData实现无刷新文件上传教程

    无刷新文件上传是一个常见而又有点复杂的问题,常见的解决方案是构造 iframe 方式实现. 在 HTML5 中提供了一个 FormData 对象 API,通过 FormData 可以方便地构造一个表单 ...

  5. iOS 中捕获截屏操作

    转自:iOS知识小集 在iOS 7后,苹果提供了UIApplicationUserDidTakeScreenshotNotification通知来告诉App用户做了截屏操作.苹果的描述如下: // T ...

  6. IPD体系向敏捷开发模式转型实施成功的四个关键因素

    文/杨学明  集成产品开发(IPD).集成能力成熟度模型(CMMI).敏捷开发(Agile Development)是当前国内外企业产品研发管理的最常用的3种模式.随着创新环境的快速发展,许多企业都会 ...

  7. Centos7 下安装VMware tools

    1:先在虚拟机点击安装VMware Tools   2:然后挂载       mount /dev/cdrom /mnt 3:进入/mnt,可以看到有       4:拷贝VMwareTools到其他 ...

  8. C&plus;&plus; new

    //#include "stdafx.h" #include <iostream> using namespace std; int main() { , n = , ...

  9. 【转载】 opencv&comma; PIL&period;Image的彩色图片维度 &amp&semi;&amp&semi; caffe和pytorch的矩阵维度

    原文地址: https://blog.csdn.net/u011668104/article/details/82718375 ------------------------------------ ...

  10. SVD分解及线性最小二乘问题

    这部分矩阵运算的知识是三维重建的数据基础. 矩阵分解 求解线性方程组:,其解可以表示为. 为了提高运算速度,节约存储空间,通常会采用矩阵分解的方案,常见的矩阵分解有LU分解.QR分解.Cholesky ...