Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Next article icon

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

Last Updated : 01 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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++




// 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);
}
 
 

Java




// 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
 
 

Python3




# 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
 
 

C#




// 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
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
   
// Function to maximize the
// count of subarrays
function maxCtSubarrays(arr, N)
{
  // Store the last index of
  // every array element
  let hash = new Array(1000001).fill(0);
  
  for (let i = 0; i < N; i++)
  {
    hash[arr[i]] = i;
  }
  
  // Store the maximum index of the
  // last occurrence of all elements
  let maxIndex = -1;
  
  // Store the count of subarrays
  let res = 0;
  
  for (let 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
 
        let arr = [1, 2, 4, 1,
               4, 7, 7, 8];
          let N = arr.length;
          document.write(maxCtSubarrays(arr, N));
 
// This code is contributed by avijitmondal1998.
</script>
 
 
Output
3

Time Complexity: O(N)
Auxiliary Space: O(X) where X = 1000001

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Split array into K subarrays such that sum of maximum of all subarrays is maximized

H

hemanthgadarla007
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • array-rearrange
  • frequency-counting
  • subarray
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

Similar Reads

  • Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
    Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8,
    7 min read
  • Count of subarrays starting or ending at an index i such that arr[i] is maximum in subarray
    Given an array arr[] consisting of N integers, the task is to find the number of subarrays starting or ending at an index i such that arr[i] is the maximum element of the subarray. Examples: Input: arr[] = {3, 4, 1, 6, 2}Output: 1 3 1 5 1Explanation: The subarray starting or ending at index 0 and wi
    11 min read
  • Split array into K subarrays such that sum of maximum of all subarrays is maximized
    Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print
    11 min read
  • Maximum length of subarray such that all elements are equal in the subarray
    Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2,
    5 min read
  • Split Array into maximum Subarrays so that sum of alternating sums is 0
    Given an array arr[] of 1s and -1s, the task is to partition the array into maximum subarrays such that the sum of the alternating sum of all the subarrays is 0. Print the ranges of the subarrays and the number of subarrays. Note: The alternating sum of a subarray a[] is defined as a[0] - a[1] + a[2
    7 min read
  • Split array into minimum number of subsets with every element of a subset divisible by its minimum
    Given an array arr[] of size N, the task is to split the array into the minimum number of subsets such that every element belongs to exactly one subset and is divisible by the minimum element present in each subset. Examples: Input: arr[] = {10, 2, 3, 5, 4, 2}Output: 3Explanation:The three possible
    7 min read
  • Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
    Given an array arr[] having N integers from the range [1, N] and an integer K, the task is to find the minimum possible cost to split the array into non-empty subarrays that can be achieved based on the following conditions: If no unique element is present in the subarray, the cost is K.Otherwise, t
    8 min read
  • Split into K subarrays to minimize the maximum sum of all subarrays
    Given an array arr[] and a number k, split the given array into k subarrays such that the maximum subarray sum achievable out of k subarrays formed is the minimum possible. The task is to find that possible subarray sum. Examples: Input: arr[] = [1, 2, 3, 4], k = 3 Output: 4 Explanation: Optimal Spl
    11 min read
  • Count ways to split an array into subarrays such that sum of the i-th subarray is divisible by i
    Given an array arr[] consisting of N integers, the task is to find the number of ways to split the array into non-empty subarrays such that the sum of the ith subarray is divisible by i. Examples: Input: arr[] = {1, 2, 3, 4}Output: 3Explanation:Following are the number of ways to split the array int
    8 min read
  • Split array to three subarrays such that sum of first and third subarray is equal and maximum
    Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be em
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences