Java Monotonic Stack O(n) Solution with Simple Explanation
IntuitionKeep the max number of each chunk in the stack in ascending order.If the current number is less than previous chunk's max number, then we should merge
# Intuition
Keep the max number of each chunk in the stack in ascending order.

If the current number is less than previous chunk's max number, then we should merge current number into the previous chunk. Here ‘previous chunk’ means the chunk currently at the top of the stack, they are represented by their max numbers.


# Complexity
- Time complexity: O(n)

- Space complexity: O(n)

# Code
```java []
class Solution {
    public int maxChunksToSorted(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        for (int i : arr) {
            int max = i;
            while (!stack.isEmpty() && stack.peek() > i) {
                max = Math.max(max, stack.pop());
            }
            stack.push(max);
        }
        return stack.size();
    }
}
```
['Monotonic Stack', 'Java']