Javascriptc | Monotonic Stack with explanation | Time O(n) | Space O(n)
Intuition\nTraverse the array from left to right, an element need to be arrange if there exists at least one element before it that greater than it. They have t
# Intuition\nTraverse the array from left to right, an element need to be arrange if there exists at least one element before it that greater than it. They have to be in the same chunk.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\n/**\n * @param {number[]} arr\n * @return {number}\n */\nvar maxChunksToSorted = function(arr) {\n  let stack = [arr[0]]; // stack[i] is the maximum element of chunk i\n  for (let i = 1; i < arr.length; i++) {\n\n    // if arr[i] greater than the last item in stack then arr[i] is a chunk.\n    if (arr[i] > stack[stack.length - 1]) { \n      stack.push(arr[i]);\n    } \n\n    // else arr[i] is a part of the chunk which is made up of all chunks whose maximum element is greater than arr[i]\n    else { \n      let maxElementOfAllChunks = stack[stack.length - 1];\n      while (arr[i] < stack[stack.length - 1]) {\n        stack.pop();\n      }\n      stack.push(maxElementOfAllChunks);\n    }\n  }\n  return stack.length\n};\n```
['Monotonic Stack', 'JavaScript']