769. Max Chunks To Make Sorted LeetCode Solution

In this guide, you will get 769. Max Chunks To Make Sorted LeetCode Solution with the best time and space complexity. The solution to Max Chunks To Make Sorted problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Max Chunks To Make Sorted solution in C++
  4. Max Chunks To Make Sorted solution in Java
  5. Max Chunks To Make Sorted solution in Python
  6. Additional Resources
769. Max Chunks To Make Sorted LeetCode Solution image

Problem Statement of Max Chunks To Make Sorted

You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n – 1].
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 = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn’t sorted.

Example 2:

Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.

Constraints:

n == arr.length
1 <= n <= 10
0 <= arr[i] < n
All the elements of arr are unique.

See also  304. Range Sum Query 2D - Immutable LeetCode Solution

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

769. Max Chunks To Make Sorted LeetCode Solution in C++

class Solution {
 public:
  int maxChunksToSorted(vector<int>& arr) {
    int ans = 0;
    int mx = INT_MIN;

    for (int i = 0; i < arr.size(); ++i) {
      mx = max(mx, arr[i]);
      if (mx == i)
        ++ans;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

769. Max Chunks To Make Sorted LeetCode Solution in Java

class Solution {
  public int maxChunksToSorted(int[] arr) {
    int ans = 0;
    int mx = Integer.MIN_VALUE;

    for (int i = 0; i < arr.length; ++i) {
      mx = Math.max(mx, arr[i]);
      if (mx == i)
        ++ans;
    }

    return ans;
  }
}
// code provided by PROGIEZ

769. Max Chunks To Make Sorted LeetCode Solution in Python

class Solution:
  def maxChunksToSorted(self, arr: list[int]) -> int:
    ans = 0
    mx = -math.inf

    for i, a in enumerate(arr):
      mx = max(mx, a)
      if mx == i:
        ans += 1

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.