LeetCode Solutions

769. Max Chunks To Make Sorted

Time: $O(n)$

Space: $O(1)$

			

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

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

    return ans;
  }
};
			

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

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

    return ans;
  }
}
			

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

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

    return ans