Suppose we have an array nums, we have to partition it into two different subarrays called left and right such that −
Each element in left subarray is less than or equal to each element in right subarray.
left and right subarrays are non-empty.
left subarray has the smallest possible size.
We have to find the length of left after such a partitioning.
So, if the input is like nums = [5,0,3,8,6], then the output will be 3 because left array will be [5,0,3] and right subarray will be [8,6].
To solve this, we will follow these steps −
mx := null, temp := null, nmx := null
temp2 := 0
for each i in nums, do
if mx is same as null, then
mx := i
nmx := i
temp := temp2
temp2 := temp2 + 1
go for next iteration
if i>=mx, then
temp2 := temp2 + 1
if i>nmx, then
nmx := i
go for next iteration
otherwise,
temp := temp2
temp2 := temp2 + 1
mx := nmx
go for next iteration
return temp+1
Example
Let us see the following implementation to get better understanding −
def solve(nums):
mx = None
temp = None
nmx = None
temp2 = 0
for i in nums:
if(mx==None):
mx = i
nmx = i
temp = temp2
temp2+=1
continue
if(i>=mx):
temp2+=1
if(i>nmx):
nmx = i
continue
else:
temp = temp2
temp2+=1
mx = nmx
continue
return temp+1
nums = [5,0,3,8,6]
print(solve(nums))Input
[5,0,3,8,6]
Output
3