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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize count of Decreasing Consecutive Subsequences from an Array
Next article icon

Maximise the size of consecutive element subsets in an array

Last Updated : 17 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an integer array and an integer k. The array elements denote positions of points on a 1-D number line, find the maximum size of the subset of points that can have consecutive values of points which can be formed by placing another k points on the number line. Note that all coordinates should be distinct and elements of the array are in increasing order.

Examples: 

Input : arr[] = {1, 2, 3, 4, 10, 11, 14, 15},             k = 4  Output : 8 For maximum size subset, it is optimal to choose the points on number line at  coordinates 12, 13, 16 and 17, so that the size of the consecutive valued subset will become 8 which will be maximum .  Input : arr[] = {7, 8, 12, 13, 15, 18}         k = 5 Output : 10 For maximum size subset, it is optimal to choose the points on number line at coordinates 9, 10,  11, 14 and 16, so that the size of the consecutive  valued subset will become 10 which will be maximum .
Recommended Practice
Maximum size of consecutives
Try It!

A brute force consists of checking all the possible (l, r) pairs for the condition ((arr[r]-arr[l])-(r-l)) ? k. In order to find out if a pair (l, r) is valid, we should check if the number of points that need to be placed between these two initial ones is not greater than K. Since arr[i] is the coordinate of the i-th point in the input array (arr), then we need to check if (arr[r] – arr[l]) – (r – l ) ? k.

Implementation:

C++




/* C++ program to find the maximum size of subset of
   points that can have consecutive values using
   brute force */
#include <bits/stdc++.h>
using namespace std;
 
int maximiseSubset(int arr[], int n, int k)
{
    // Since we can always enforce the solution
    // to contain all the K added points
    int ans = k;
 
    for (int l = 0; l < n - 1; l++)
        for (int r = l; r < n; r++)
 
            // check if the number of points that
            // need to be placed between these two
            // initial ones is not greater than k
            if ((arr[r] - arr[l]) - (r - l) <= k)
                ans = max(ans, r - l + k + 1);
 
    return (ans);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 10, 11, 14, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    printf("%dn", maximiseSubset(arr, n, k));
    return 0;
}
 
 

Java




/* Java program to find the maximum size of subset of
points that can have consecutive values using
brute force */
import java.util.*;
 
class GFG
{
 
    static int maximiseSubset(int[] arr, int n, int k)
    {
        // Since we can always enforce the solution
        // to contain all the K added points
        int ans = k;
 
        for (int l = 0; l < n - 1; l++)
            for (int r = l; r < n; r++)
 
                // check if the number of points that
                // need to be placed between these two
                // initial ones is not greater than k
                if ((arr[r] - arr[l]) - (r - l) <= k)
                    ans = Math.max(ans, r - l + k + 1);
 
        return (ans);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 10, 11, 14, 15 };
        int n = arr.length;
        int k = 4;
        System.out.println(maximiseSubset(arr, n, k)); 
    }
}
/* This code is contributed by Mr. Somesh Awasthi */
 
 

Python3




# Python3 program to find the maximum size
# of subset of points that can have consecutive
# values using brute force
 
def maximiseSubset(arr , n, k):
 
    # Since we can always enforce the solution
    # to contain all the K added points
    ans = k
 
    for l in range(n - 1):
        for r in range(l, n):
 
            # check if the number of points that
            # need to be placed between these two
            # initial ones is not greater than k
            if ((arr[r] - arr[l]) - (r - l) <= k) :
                ans = max(ans, r - l + k + 1)
 
    return (ans)
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 1, 2, 3, 4, 10, 11, 14, 15 ]
    n = len(arr)
    k = 4
    print(maximiseSubset(arr, n, k))
 
# This code is contributed by ita_c
 
 

C#




/* C# program to find the
maximum size of subset of
points that can have
consecutive values using
brute force */
using System;
 
class GFG
{
 
    static int maximiseSubset(int[] arr,
                              int n, int k)
    {
        // Since we can always enforce
        // the solution to contain all
        // the K added points
        int ans = k;
 
        for (int l = 0; l < n - 1; l++)
            for (int r = l; r < n; r++)
 
                // check if the number of
                // points that need to be
                // placed between these
                // two initial ones is not
                // greater than k
                if ((arr[r] - arr[l]) -
                              (r - l) <= k)
                    ans = Math.Max(ans, r - l +
                                        k + 1);
 
        return (ans);
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = {1, 2, 3, 4,
                    10, 11, 14, 15};
        int n = arr.Length;
        int k = 4;
        Console.WriteLine(maximiseSubset(arr, n, k));
    }
}
 
// This code is contributed by anuj_67.
 
 

PHP




<?php
// PHP program to find the maximum size
// of subset of points that can have 
// consecutive values using brute force
function maximiseSubset($arr, $n, $k)
{
    // Since we can always enforce
    // the solution to contain all
    // the K added points
    $ans = $k;
 
    for ($l = 0; $l < $n - 1; $l++)
        for ($r = $l; $r < $n; $r++)
 
            // check if the number of points that
            // need to be placed between these two
            // initial ones is not greater than k
            if (($arr[$r] - $arr[$l]) -
                ($r - $l) <= $k)
                $ans = max($ans, $r - $l + $k + 1);
 
    return ($ans);
}
 
// Driver code
$arr = array(1, 2, 3, 4, 10, 11, 14, 15 );
$n = sizeof($arr);
$k = 4;
echo (maximiseSubset($arr, $n, $k));
 
// This code is contributed
// by Sach_Code   
?>
 
 

Javascript




<script>
 
// Javascript program to find the
// maximum size of subset of points
// that can have consecutive values using
// brute force
function maximiseSubset(arr, n, k)
{
     
    // Since we can always enforce the
    // solution to contain all the K
    // added points
    let ans = k;
 
    for(let l = 0; l < n - 1; l++)
        for(let r = l; r < n; r++)
         
            // Check if the number of points that
            // need to be placed between these two
            // initial ones is not greater than k
            if ((arr[r] - arr[l]) - (r - l) <= k)
                ans = Math.max(ans, r - l + k + 1);
 
    return (ans);
}
 
// Driver code
let arr = [ 1, 2, 3, 4, 10, 11, 14, 15 ];
let n = arr.length;
let k = 4;
 
document.write(maximiseSubset(arr, n, k)); 
 
// This code is contributed by avanitrachhadiya2155
     
</script>
 
 
Output
8n

Time complexity: O(N2).
Auxiliary Space: O(1)

Efficient Approach:

In order to optimize the brute force, notice that if r increases, then l also increases (or at least stays the same). We can maintain two indexes. Initialize l and r both as 0. Then we start incrementing r. As we do this, at each step we increment l until the condition used in the brute force approach becomes true. When r reaches the last index, we stop. 

Implementation:

C++




/* C++ program to find the maximum size of subset
   of points that can have consecutive values
   using efficient approach */
#include <bits/stdc++.h>
using namespace std;
 
int maximiseSubset(int arr[], int n, int k)
{
    // Since we can always enforce the
    // solution to contain all the K added
    // points
    int ans = k;
 
    int l = 0, r = 0;
    while (r < n) {
 
        // increment l until the number of points
        // that need to be placed between index l
        // and index r is not greater than k
        while ((arr[r] - arr[l]) - (r - l) > k)
            l++;
         
        // update the solution as below
        ans = max(ans, r - l + k + 1);
         
        r++;
    }
 
    return (ans);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 10, 11, 14, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    printf("%d", maximiseSubset(arr, n, k));
    return 0;
}
 
 

Java




/* Java program to find the maximum size of subset
of points that can have consecutive values
using efficient approach */
import java.util.*;
 
class GFG
{
    static int maximiseSubset(int[] arr, int n, int k)
    {
        // Since we can always enforce the
        // solution to contain all the K added
        // points
        int ans = k;
 
        int l = 0, r = 0;
        while (r < n) {
 
            // increment l until the number of points
            // that need to be placed between index l
            // and index r is not greater than k
            while ((arr[r] - arr[l]) - (r - l) > k)
                l++;
         
            // update the solution as below
            ans = Math.max(ans, r - l + k + 1);
         
            r++;
        }
 
        return (ans);
    }
 
    // Driver code 
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 10, 11, 14, 15 };
        int n = arr.length;
        int k = 4;
        System.out.println(maximiseSubset(arr, n, k));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */
 
 

Python3




# Python 3 program to find the maximum size
# of subset of points that can have consecutive
# values using efficient approach
def maximiseSubset(arr, n, k):
 
    # Since we can always enforce the solution
    # to contain all the K added points
    ans = k;
 
    l = 0; r = 0;
    while (r < n):
 
        # increment l until the number of points
        # that need to be placed between index l
        # and index r is not greater than k
        while ((arr[r] - arr[l]) - (r - l) > k):
            l = l + 1;
         
        # update the solution as below
        ans = max(ans, r - l + k + 1);
         
        r = r + 1;
         
    return (ans);
 
# Driver code
arr = [ 1, 2, 3, 4, 10, 11, 14, 15 ];
n = len(arr);
k = 4;
print(maximiseSubset(arr, n, k));
 
# This code is contributed
# by Akanksha Rai
 
 

C#




/* C# program to find the
maximum size of subset
of points that can have
consecutive values using
efficient approach */
using System;
 
class GFG
{
    static int maximiseSubset(int[] arr,
                              int n, int k)
    {
        // Since we can always enforce
        // the solution to contain all
        // the K added points
        int ans = k;
 
        int l = 0, r = 0;
        while (r < n)
        {
 
            // increment l until the
            // number of points that
            // need to be placed
            // between index l and
            // index r is not greater
            // than k
            while ((arr[r] - arr[l]) -
                        (r - l) > k)
                l++;
         
            // update the
            // solution as below
            ans = Math.Max(ans, r - l +
                                k + 1);
         
            r++;
        }
 
        return (ans);
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = {1, 2, 3, 4,
                    10, 11, 14, 15};
        int n = arr.Length;
        int k = 4;
        Console.WriteLine(maximiseSubset(arr, n, k));
    }
}
 
// This code is contributed
// by anuj_67.
 
 

PHP




<?php
// PHP program to find the maximum size
// of subset of points that can have
// consecutive values using efficient approach
function maximiseSubset($arr, $n, $k)
{
    // Since we can always enforce the
    // solution to contain all the K
    // added points
    $ans = $k;
 
    $l = 0; $r = 0;
    while ($r < $n)
    {
 
        // increment l until the number of points
        // that need to be placed between index l
        // and index r is not greater than k
        while (($arr[$r] - $arr[$l]) -
               ($r - $l) > $k)
            $l++;
     
        // update the solution as below
        $ans = max($ans, $r - $l + $k + 1);
     
        $r++;
    }
 
    return ($ans);
}
 
// Driver code
$arr = array(1, 2, 3, 4, 10, 11, 14, 15 );
$n = sizeof($arr);
$k = 4;
echo(maximiseSubset($arr, $n, $k));
 
// This code is contributed by Mukul Singh
?>
 
 

Javascript




<script>
/* Javascript program to find the maximum size of subset
of points that can have consecutive values
using efficient approach */
 
    function maximiseSubset(arr,n,k)
    {
        // Since we can always enforce the
        // solution to contain all the K added
        // points
        let ans = k;
  
        let l = 0, r = 0;
        while (r < n) {
  
            // increment l until the number of points
            // that need to be placed between index l
            // and index r is not greater than k
            while ((arr[r] - arr[l]) - (r - l) > k)
                l++;
          
            // update the solution as below
            ans = Math.max(ans, r - l + k + 1);
          
            r++;
        }
  
        return (ans);
    }
     
    // Driver code
    let arr=[1, 2, 3, 4, 10, 11, 14, 15 ];
    let n = arr.length;
    let k = 4;
    document.write(maximiseSubset(arr, n, k));
     
    // This code is contributed by rag2127
</script>
 
 
Output
8

Time Complexity: O(N) 
Auxiliary Space: O(1)

 



Next Article
Maximize count of Decreasing Consecutive Subsequences from an Array
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • Misc
Practice Tags :
  • Arrays
  • Misc

Similar Reads

  • Check if an array can be split into subsets of K consecutive elements
    Given an array arr[] and integer K, the task is to split the array into subsets of size K, such that each subset consists of K consecutive elements. Examples: Input: arr[] = {1, 2, 3, 6, 2, 3, 4, 7, 8}, K = 3 Output: true Explanation: The given array of length 9 can be split into 3 subsets {1, 2, 3}
    5 min read
  • Maximum sum of Subset having no consecutive elements
    Given an array arr[] of size N, the task is to find the maximum possible sum of a subset of the array such that no two consecutive elements are part of the subset. Examples: Input: arr[]= {2, 3, 2, 3, 3, 4}Output: 9Explanation: The subset having all the 3s i.e. {3, 3, 3} have sum = 9.This is the max
    9 min read
  • Maximize count of distinct elements in a subsequence of size K in given array
    Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
    4 min read
  • Size of the largest divisible subset in an Array
    Given an array arr[] of size N. The task is to find the size of the set of numbers from the given array such that each number divides another or is divisible by another.Examples: Input : arr[] = {3, 4, 6, 8, 10, 18, 21, 24} Output : 3 One of the possible sets with a maximum size is {3, 6, 18} Input
    5 min read
  • Maximize count of Decreasing Consecutive Subsequences from an Array
    Given an array arr[] consisting of N integers, the task is to find the maximum count of decreasing subsequences possible from an array that satisfies the following conditions: Each subsequence is in its longest possible form.The difference between adjacent elements of the subsequence is always 1. Ex
    8 min read
  • Maximize sum of subsets from two arrays having no consecutive values
    Given two arrays arr1[] and arr2[] of equal length, the task is to find the maximum sum of any subset possible by selecting elements from both the arrays such that no two elements in the subset should be consecutive. Examples: Input: arr1[] = {-1, -2, 4, -4, 5}, arr2[] = {-1, -2, -3, 4, 10}Output: 1
    10 min read
  • Maximum number of consecutive 1's in binary representation of all the array elements
    Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
    6 min read
  • Maximum consecutive numbers present in an array
    Find the length of maximum number of consecutive numbers jumbled up in an array.Examples: Input : arr[] = {1, 94, 93, 1000, 5, 92, 78};Output : 3 The largest set of consecutive elements is92, 93, 94 Input : arr[] = {1, 5, 92, 4, 78, 6, 7};Output : 4 The largest set of consecutive elements is4, 5, 6,
    15+ min read
  • Maximum subsequence sum such that no K elements are consecutive
    Given an array arr[] of N positive integers, the task is to find the maximum sum of a subsequence consisting of no K consecutive array elements. Examples: Input: arr[] = {10, 5, 8, 16, 21}, K = 4Output: 55Explanation:Maximum sum is obtained by picking 10, 8, 16, 21. Input: arr[] = {4, 12, 22, 18, 34
    9 min read
  • Maximize sum of consecutive differences in a circular array
    Given an array of n elements. Consider array as circular array i.e element after an is a1. The task is to find maximum sum of the difference between consecutive elements with rearrangement of array element allowed i.e after rearrangement of element find |a1 - a2| + |a2 - a3| + ...... + |an - 1 - an|
    5 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