# Program to find max chunks to make array sorted in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array nums, we have to split the array into some number of partitions, and individually sort each of them. Now after concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made?

So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], [4], [5], [5] .

To solve this, we will follow these steps −

• real:= sort the list nums

• p1 := 0,p2 := 1, c := 0

• Do the following infinitely, do

• flag:= True

• tmp:= sort the sublist of nums[from index p1 to p2-1]

• for j in range 0 to size of tmp, do

• if tmp[j] is not same as real[p1+j], then

• flag:= False

• p2 := p2 + 1

• come out from loop

• if flag is true, then

• p1 := p2

• p2:= p2+1

• c := c + 1

• if p1 is same as size of nums or p2 > size of nums, then

• return c

## Example

Let us see the following implementation to get better understanding

def solve(nums):
real=sorted(nums)
p1,p2,c=0,1,0
while True:

flag=True
tmp=sorted(nums[p1:p2])
for j in range(len(tmp)):
if tmp[j]!=real[p1+j]:
flag=False
p2+=1
break

if flag:
p1,p2=p2,p2+1
c+=1
if p1==len(nums) or p2>len(nums):
return c

nums = [3,2,4,5,5]
print(solve(nums))

## Input

{3,2,4,5,5}


## Output

4
Updated on 08-Oct-2021 07:34:58