Last updated on October 9th, 2024 at 06:28 pm
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
Topics
Greedy, Two-Pointers
Level of Question
Hard
Max Chunks To Make Sorted II LeetCode Solution
Table of Contents
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.
1. 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; } };
2. Max Chunks To Make Sorted II LeetCode Solution Java
class Solution { public int maxChunksToSorted(int[] arr) { Stack<Integer> a= new Stack<Integer>(); for(int i=0;i<arr.length;i++) { int mx=arr[i]; while(!a.isEmpty()&&arr[i]<a.peek()) { mx= Math.max(mx,a.peek()); a.pop(); } a.push(mx); } return(a.size()); } }
3. Max Chunks To Make Sorted II LeetCode Solution JavaScript
var maxChunksToSorted = function(arr) { let stack = [arr[0]]; for (let i = 1; i < arr.length; i++) { if (arr[i] > stack[stack.length - 1]) { stack.push(arr[i]); } else { let maxElementOfAllChunks = stack[stack.length - 1]; while (arr[i] < stack[stack.length - 1]) { stack.pop(); } stack.push(maxElementOfAllChunks); } } return stack.length };
4. 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)