LeetCode 0768. Max Chunks To Make Sorted II Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0768. Max Chunks To Make Sorted II

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.

 

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.

 

Constraints:

  • 1 <= arr.length <= 2000
  • 0 <= arr[i] <= 108

Solutions

Solution 1: Monotonic Stack

According to the problem, we can find that from left to right, each chunk has a maximum value, and these maximum values are monotonically increasing (non-strictly increasing). We can use a stack to store these maximum values of the chunks. The size of the final stack is the maximum number of chunks that can be sorted.

Time complexity is O(n), where n represents the length of arr.

PythonJavaC++GoTypeScriptRust
class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: stk = [] for v in arr: if not stk or v >= stk[-1]: stk.append(v) else: mx = stk.pop() while stk and stk[-1] > v: stk.pop() stk.append(mx) return len(stk)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !