768. Max Chunks To Make Sorted II

1. Description

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.

2. Example

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.

3. Constraints

  • 1 <= arr.length <= 2000
  • 0 <= arr[i] <= $10^8$

4. Solutions

Sort & Prefix Sum

n = arr.size()
Time complexity: O(nlogn)
Space complexity: O(n)

Monotonic Stack

n = arr.size()
Time complexity: O(n)
Space complexity: O(n)

class Solution {
public:
    int maxChunksToSorted(const vector<int> &arr) {
        stack<int> increase_data;
        for (auto num : arr) {
            if (increase_data.empty() || num >= increase_data.top()) {
                increase_data.push(num);
            } else {
                int top_value = increase_data.top();
                increase_data.pop();

                while (!increase_data.empty() && increase_data.top() > num) {
                    increase_data.pop();
                }

                increase_data.push(top_value);
            }
        }

        return increase_data.size();
    }
};
comments powered by Disqus