Given an array arr[] of size n such that elements of arr[] in range [0, 1, ..n-1] where every number is present at most once. Our task is to divide the array into maximum number of partitions that can be sorted individually, then concatenated to make the whole array sorted.
Examples :
Input : arr[] = [2, 1, 0, 3]
Output : 2
If divide arr[] into two partitions
{2, 1, 0} and {3}, sort then and concatenate
then, we get the whole array sorted.
Input : arr[] = [2, 1, 0, 3, 4, 5]
Output : 4
The maximum number of partitions are four, we
get these partitions as {2, 1, 0}, {3}, {4}
and {5}
Input : arr[] = [0, 1, 2, 3, 4, 5]
Output : 6
The maximum number of partitions are six, we
get these partitions as {0}, {1}, {2}, {3}, {4}
and {5}
The idea is based on the fact that if an element at i is maximum of prefix arr[0..i], then we can make a partition ending with i.
C++
#include <bits/stdc++.h>
using namespace std;
int maxPartitions( int arr[], int n)
{
int ans = 0, max_so_far = 0;
for ( int i = 0; i < n; ++i) {
max_so_far = max(max_so_far, arr[i]);
if (max_so_far == i)
ans++;
}
return ans;
}
int main()
{
int arr[] = { 1, 0, 2, 3, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxPartitions(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int maxPartitions( int arr[], int n)
{
int ans = 0 , max_so_far = 0 ;
for ( int i = 0 ; i < n; ++i) {
max_so_far = Math.max(max_so_far, arr[i]);
if (max_so_far == i)
ans++;
}
return ans;
}
public static void main (String[] args)
{
int arr[] = { 1 , 0 , 2 , 3 , 4 };
int n = arr.length;
System.out.println (maxPartitions(arr, n));
}
}
|
Python3
def maxPartitions(arr, n):
ans = 0 ; max_so_far = 0
for i in range ( 0 , n):
max_so_far = max (max_so_far, arr[i])
if (max_so_far = = i):
ans + = 1
return ans
arr = [ 1 , 0 , 2 , 3 , 4 ]
n = len (arr)
print (maxPartitions(arr, n))
|
C#
using System;
class GFG
{
static int maxPartitions( int []arr, int n)
{
int ans = 0, max_so_far = 0;
for ( int i = 0; i < n; ++i)
{
max_so_far = Math.Max(max_so_far, arr[i]);
if (max_so_far == i)
ans++;
}
return ans;
}
public static void Main ()
{
int []arr = { 1, 0, 2, 3, 4 };
int n = arr.Length;
Console.Write (maxPartitions(arr, n));
}
}
|
PHP
<?php
function maxPartitions( $arr , $n )
{
$ans = 0;
$max_so_far = 0;
for ( $i = 0; $i < $n ; ++ $i ) {
$max_so_far = max( $max_so_far , $arr [ $i ]);
if ( $max_so_far == $i )
$ans ++;
}
return $ans ;
}
{
$arr = array (1, 0, 2, 3, 4);
$n = sizeof( $arr ) / sizeof( $arr [0]);
echo maxPartitions( $arr , $n );
return 0;
}
?>
|
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.