# Max Chunks To Make Sorted II LeetCode Solution

Here, We see Max Chunks To Make Sorted II LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

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.

## Max Chunks To Make Sorted II LeetCode Solution C++

class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int n = arr.size();
vector<int> left_max(n, 0);
left_max[0] = arr[0];
for(int i = 1; i < n; i++)
{
left_max[i] = max(left_max[i - 1], arr[i]);
}
vector<int> right_min(n, 0);
right_min[n - 1] = arr[n - 1];
for(int i = n - 2; i >= 0; i--)
{
right_min[i] = min(right_min[i + 1], arr[i]);
}
int count = 0;
for(int i = 0; i < n - 1; i++)
{
if(left_max[i] <= right_min[i + 1])
{
count++;
}
}
count++;
return count;
}
};Code language: PHP (php)

## Max Chunks To Make Sorted II LeetCode Solution Java

class Solution {
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int[] maxTillNow = new int[n];
int[] minOnRight = new int[n];
maxTillNow[0] = arr[0];
for(int i=1; i<n; i++){
maxTillNow[i] = Math.max(arr[i], maxTillNow[i-1]);
}
minOnRight[n-1] = arr[n-1];
for(int i=n-2; i>=0; i--){
minOnRight[i] = Math.min(arr[i], minOnRight[i+1]);
}
int result = 0;
for(int i = 0; i < n-1; i++){
if(maxTillNow[i] <= minOnRight[i+1]){
result++;
}
}
return result+1;
}
}Code language: JavaScript (javascript)

## Max Chunks To Make Sorted II LeetCode Solution JavaScript

var maxChunksToSorted = function (arr) {
let maxVal = Number.MIN_SAFE_INTEGER;
let min = new Array(arr.length);
let max = new Array(arr.length);
max[0] = maxVal;
for (let i = 1; i < arr.length; i++) {
max[i] = Math.max(max[i - 1], arr[i - 1])
}
min[arr.length - 1] = arr[arr.length - 1];
for (let i = arr.length - 2; i >= 0; i--) {
min[i] = Math.min(min[i + 1], arr[i])
}
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (max[i] <= min[i]) count++;
}
return count;
};Code language: JavaScript (javascript)

## Max Chunks To Make Sorted II LeetCode Solution Python

class Solution(object):
def maxChunksToSorted(self, arr):
stack = []
for num in arr:
m = num
while stack and num < stack[-1]:
m = max(m, stack.pop())
stack.append(m)
return len(stack)   Code language: HTML, XML (xml)
Scroll to Top