zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    软件需求模式阅读笔记02
    软件需求模式阅读笔记1
    问题账户需求分析
    浅谈软件架构师的工作过程
    架构之美阅读笔记五
    架构之美阅读笔记四
    架构之美阅读笔记三
    架构之美阅读笔记二
    架构之美阅读笔记一
    软件需求与分析课堂讨论一
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11367324.html
Copyright © 2011-2022 走看看