Skip to content

Latest commit

 

History

History
66 lines (54 loc) · 1.57 KB

File metadata and controls

66 lines (54 loc) · 1.57 KB

769. Max Chunks To Make Sorted

Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

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.

Note:

  • arr will have length in range [1, 10].
  • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].

Solutions (Ruby)

1. Solution

# @param {Integer[]} arr
# @return {Integer}
def max_chunks_to_sorted(arr)
  x = 0
  ret = 0

  (0...arr.size).each do |i|
    x ^= 1 << arr[i]
    ret += 1 if x == (2 << i) - 1
  end

  ret
end

Solutions (Rust)

1. Solution

impl Solution {
    pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
        let mut x = 0;
        let mut ret = 0;

        for i in 0..arr.len() {
            x ^= 1 << arr[i];
            if x == (2 << i) - 1 {
                ret += 1;
            }
        }

        ret
    }
}