Algorithm


Problem Name: 768. Max Chunks To Make Sorted II

You are given an integer array arr.

We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return the largest number of chunks we can make to sort the array.

 

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.

 

Constraints:

  • 1 <= arr.length <= 2000
  • 0 <= arr[i] <= 108

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const maxChunksToSorted = function(arr) {
  const clonedArr = arr.slice(0);
  let sum1 = 0;
  let sum2 = 0;
  let res = 0;
  clonedArr.sort((a, b) => a - b);
  for (let i = 0; i  <  arr.length; i++) {
    sum1 += arr[i];
    sum2 += clonedArr[i];
    if (sum1 === sum2) res += 1;
  }
  return res;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
arr = [5,4,3,2,1]

Output

x
+
cmd
1

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def maxChunksToSorted(self, arr):
        mx, mn, res, check = 0, 10 ** 9, 0, [[0, 0] for _ in range(len(arr))]
        for i in range(len(arr)):
            if arr[i] > mx: mx = arr[i]
            check[i][0] = mx
        for i in range(len(arr) -1, -1, -1):
            check[i][1] = mn
            if arr[i] < mn: mn = arr[i]
        for c in check:
            if c[0] <= c[1]: res += 1
        return res
Copy The Code & Try With Live Editor

Input

x
+
cmd
arr = [5,4,3,2,1]

Output

x
+
cmd
1
Advertisements

Demonstration


Previous
#767 Leetcode Reorganize String Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#769 Leetcode Max Chunks To Make Sorted Solution in C, C++, Java, JavaScript, Python, C# Leetcode