Split array into maximum subarrays such that every distinct element lies in a single subarray

Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray.

Examples:

Input: arr[] = {1, 1, 2, 2}
Output: 2
Explanation:
Split the array into subarrays {1, 1} and {2, 2}.
Therefore, the required output is 2.

Input: arr[] = {1, 2, 4, 1, 4, 7, 7, 8}
Output: 3
Explanation:
Split the array into subarrays {1, 2, 4, 1, 4}, {7, 7} and {8}.
Therefore, the required output is 3.

Approach: The idea is to use Hashing to store the index of the last occurrence of every array element. Follow the steps below to solve the problem:



  1. Initialize an array, say hash[] to store the index of the last occurrence of every array element.
  2. Traverse the array and check if the maximum index of the last occurrence of all the previous elements of the current subarray is less than or equal to the current index, then increment the count by 1.
  3. Finally, print the value of count.

Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the
// count of subarrays
int maxCtSubarrays(int arr[], int N)
{
    // Store the last index of
    // every array element
    int hash[1000001] = { 0 };
 
    for (int i = 0; i < N; i++) {
        hash[arr[i]] = i;
    }
 
    // Store the maximum index of the
    // last occurrence of all elements
    int maxIndex = -1;
 
    // Store the count of subarrays
    int res = 0;
 
    for (int i = 0; i < N; i++) {
        maxIndex = max(maxIndex,
                       hash[arr[i]]);
 
        // If maximum of last indices
        // previous elements is equal
        // to the current index
        if (maxIndex == i) {
            res++;
        }
    }
 
    // Return the count
    // of subarrays
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 4, 1,
                  4, 7, 7, 8 };
    int N = sizeof(arr)
            / sizeof(arr[0]);
 
    cout << maxCtSubarrays(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GFG {
 
// Function to maximize the
// count of subarrays
static int maxCtSubarrays(int arr[],
                          int N)
{
  // Store the last index of
  // every array element
  int hash[] = new int[1000001];
 
  for (int i = 0; i < N; i++)
  {
    hash[arr[i]] = i;
  }
 
  // Store the maximum index of the
  // last occurrence of all elements
  int maxIndex = -1;
 
  // Store the count of subarrays
  int res = 0;
 
  for (int i = 0; i < N; i++)
  {
    maxIndex = Math.max(maxIndex,
                        hash[arr[i]]);
 
    // If maximum of last indices
    // previous elements is equal
    // to the current index
    if (maxIndex == i)
    {
      res++;
    }
  }
 
  // Return the count
  // of subarrays
  return res;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 4, 1,
               4, 7, 7, 8};
  int N = arr.length;
  System.out.print(maxCtSubarrays(arr, N));
}
}
 
// This code is contributed by Chitranayal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to maximize the
# count of subarrays
def maxCtSubarrays(arr, N):
     
    # Store the last index of
    # every array element
    hash = [0] * (1000001)
 
    for i in range(N):
        hash[arr[i]] = i
 
    # Store the maximum index of the
    # last occurrence of all elements
    maxIndex = -1
 
    # Store the count of subarrays
    res = 0
 
    for i in range(N):
        maxIndex = max(maxIndex,
                       hash[arr[i]])
 
        # If maximum of last indices
        # previous elements is equal
        # to the current index
        if (maxIndex == i):
            res += 1
 
    # Return the count
    # of subarrays
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 4, 1,
            4, 7, 7, 8 ]
    N = len(arr)
 
    print(maxCtSubarrays(arr, N))
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG {
 
// Function to maximize the
// count of subarrays
static int maxCtSubarrays(int []arr,
                          int N)
{
  // Store the last index of
  // every array element
  int []hash = new int[1000001];
 
  for (int i = 0; i < N; i++)
  {
    hash[arr[i]] = i;
  }
 
  // Store the maximum index of the
  // last occurrence of all elements
  int maxIndex = -1;
 
  // Store the count of subarrays
  int res = 0;
 
  for (int i = 0; i < N; i++)
  {
    maxIndex = Math.Max(maxIndex,
                        hash[arr[i]]);
 
    // If maximum of last indices
    // previous elements is equal
    // to the current index
    if (maxIndex == i)
    {
      res++;
    }
  }
 
  // Return the count
  // of subarrays
  return res;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 2, 4, 1,
               4, 7, 7, 8};
  int N = arr.Length;
  Console.Write(maxCtSubarrays(arr, N));
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output

3

Time Complexity: O(N)
Auxiliary Space: O(X) where X, is the maximum element in the given array.

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.