Max Chunks To Make Sorted II

hard monotonic-stack stack arrays

Problem

Given an array with possible duplicates, split it into the maximum number of chunks such that sorting each chunk individually and concatenating yields the sorted array.

Inputarr=[5,4,3,2,1]
Output1
No partition besides the whole array works.

def maxChunksToSorted(arr):
    stack = []
    for x in arr:
        if not stack or x >= stack[-1]:
            stack.append(x)
        else:
            top = stack.pop()
            while stack and stack[-1] > x:
                stack.pop()
            stack.append(top)
    return len(stack)
function maxChunksToSorted(arr) {
  const stack = [];
  for (const x of arr) {
    if (!stack.length || x >= stack[stack.length-1]) stack.push(x);
    else {
      const top = stack.pop();
      while (stack.length && stack[stack.length-1] > x) stack.pop();
      stack.push(top);
    }
  }
  return stack.length;
}
int maxChunksToSorted(int[] arr) {
    Deque<Integer> stack = new ArrayDeque<>();
    for (int x : arr) {
        if (stack.isEmpty() || x >= stack.peek()) stack.push(x);
        else {
            int top = stack.pop();
            while (!stack.isEmpty() && stack.peek() > x) stack.pop();
            stack.push(top);
        }
    }
    return stack.size();
}
int maxChunksToSorted(vector<int>& arr) {
    stack<int> st;
    for (int x : arr) {
        if (st.empty() || x >= st.top()) st.push(x);
        else {
            int top = st.top(); st.pop();
            while (!st.empty() && st.top() > x) st.pop();
            st.push(top);
        }
    }
    return st.size();
}
Time: O(n) Space: O(n)