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:
Longest subarray not having more than K distinct elements
Next article icon

Maximize length of subarray having equal elements by adding at most K

Last Updated : 05 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N positive integers and an integer K, which represents the maximum number that can be added to the array elements. The task is to maximize the length of the longest possible subarray of equal elements by adding at most K.

Examples:

Input: arr[] = {3, 0, 2, 2, 1}, k = 3
Output: 4
Explanation: 
Step 1: Adding 2 to arr[1] modifies array to {3, 2, 2, 2, 1}
Step 2: Adding 1 to arr[4] modifies array to {3, 2, 2, 2, 2}
Therefore, answer will be 4 ({arr[1], …, arr[4]}).

Input: arr[] = {1, 1, 1}, k = 7
Output: 3
Explanation:
All array elements are already equal. Therefore, the length is 3.

 

Approach: Follow the steps below to solve the problem:

  • Sort the array arr[]. Then, use Binary Search to pick a possible value for the maximum indices having the same element.
  • For each picked_value, use the Sliding Window technique to check if it is possible to make all elements equal for any subarray of size picked_value.
  • Finally, print the longest possible length of subarray obtained.

Below is the implementation for the above approach:

C++14




// C++14 program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a subarray of
// length len consisting of equal elements
// can be obtained or not
bool check(vector<int> pSum, int len, int k,
           vector<int> a)
{
     
    // Sliding window
    int i = 0;
    int j = len;
     
    while (j <= a.size())
    {
         
        // Last element of the sliding window
        // will be having the max size in the
        // current window
        int maxSize = a[j - 1];
 
        int totalNumbers = maxSize * len;
 
        // The current number of element in all
        // indices of the current sliding window
        int currNumbers = pSum[j] - pSum[i];
 
        // If the current number of the window,
        // added to k exceeds totalNumbers
        if (currNumbers + k >= totalNumbers)
        {
            return true;
        }
        else
        {
            i++;
            j++;
        }
    }
    return false;
}
 
// Function to find the maximum number of
// indices having equal elements after
// adding at most k numbers
int maxEqualIdx(vector<int> arr, int k)
{
     
    // Sort the array in
    // ascending order
    sort(arr.begin(), arr.end());
 
    // Make prefix sum array
    vector<int> prefixSum(arr.size());
    prefixSum[1] = arr[0];
 
    for(int i = 1;
            i < prefixSum.size() - 1; ++i)
    {
        prefixSum[i + 1] = prefixSum[i] +
                                 arr[i];
    }
 
    // Initialize variables
    int max = arr.size();
    int min = 1;
    int ans = 1;
 
    while (min <= max)
    {
         
        // Update mid
        int mid = (max + min) / 2;
 
        // Check if any subarray
        // can be obtained of length
        // mid having equal elements
        if (check(prefixSum, mid, k, arr))
        {
            ans = mid;
            min = mid + 1;
        }
        else
        {
             
            // Decrease max to mid
            max = mid - 1;
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 1, 1 };
    int k = 7;
 
    // Function call
    cout << (maxEqualIdx(arr, k));
}
 
// This code is contributed by mohit kumar 29
 
 

Java




// Java program for above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find the maximum number of
    // indices having equal elements after
    // adding at most k numbers
    public static int maxEqualIdx(int[] arr,
                                  int k)
    {
        // Sort the array in
        // ascending order
        Arrays.sort(arr);
 
        // Make prefix sum array
        int[] prefixSum
            = new int[arr.length + 1];
        prefixSum[1] = arr[0];
 
        for (int i = 1; i < prefixSum.length - 1;
             ++i) {
 
            prefixSum[i + 1]
                = prefixSum[i] + arr[i];
        }
 
        // Initialize variables
        int max = arr.length;
        int min = 1;
        int ans = 1;
 
        while (min <= max) {
 
            // Update mid
            int mid = (max + min) / 2;
 
            // Check if any subarray
            // can be obtained of length
            // mid having equal elements
            if (check(prefixSum, mid, k, arr)) {
 
                ans = mid;
                min = mid + 1;
            }
            else {
 
                // Decrease max to mid
                max = mid - 1;
            }
        }
 
        return ans;
    }
 
    // Function to check if a subarray of
    // length len consisting of equal elements
    // can be obtained or not
    public static boolean check(int[] pSum,
                                int len, int k,
                                int[] a)
    {
 
        // Sliding window
        int i = 0;
        int j = len;
        while (j <= a.length) {
 
            // Last element of the sliding window
            // will be having the max size in the
            // current window
            int maxSize = a[j - 1];
 
            int totalNumbers = maxSize * len;
 
            // The current number of element in all
            // indices of the current sliding window
            int currNumbers = pSum[j] - pSum[i];
 
            // If the current number of the window,
            // added to k exceeds totalNumbers
            if (currNumbers + k >= totalNumbers) {
 
                return true;
            }
            else {
                i++;
                j++;
            }
        }
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int[] arr = { 1, 1, 1 };
        int k = 7;
 
        // Function call
        System.out.println(maxEqualIdx(arr, k));
    }
}
 
 

Python3




# Python3 program for above approach
  
# Function to find the maximum number of
# indices having equal elements after
# adding at most k numbers
def maxEqualIdx(arr, k):
     
    # Sort the array in
    # ascending order
    arr.sort()
     
    # Make prefix sum array
    prefixSum = [0] * (len(arr) + 1)
    prefixSum[1] = arr[0]
  
    for i in range(1, len(prefixSum) - 1 ,1):
        prefixSum[i + 1] = prefixSum[i] + arr[i]
   
    # Initialize variables
    max = len(arr)
    min = 1
    ans = 1
  
    while (min <= max):
         
        # Update mid
        mid = (max + min) // 2
  
        # Check if any subarray
        # can be obtained of length
        # mid having equal elements
        if (check(prefixSum, mid, k, arr)):
            ans = mid
            min = mid + 1
        else:
             
            # Decrease max to mid
            max = mid - 1
     
    return ans
 
# Function to check if a subarray of
# length len consisting of equal elements
# can be obtained or not
def check(pSum, lenn, k, a):
     
    # Sliding window
    i = 0
    j = lenn
     
    while (j <= len(a)):
       
        # Last element of the sliding window
        # will be having the max size in the
        # current window
        maxSize = a[j - 1]
  
        totalNumbers = maxSize * lenn
  
        # The current number of element in all
        # indices of the current sliding window
        currNumbers = pSum[j] - pSum[i]
  
        # If the current number of the window,
        # added to k exceeds totalNumbers
        if (currNumbers + k >= totalNumbers):
            return True
     
        else:
            i += 1
            j += 1
     
    return False
 
# Driver Code
 
arr = [ 1, 1, 1 ]
k = 7
  
# Function call
print(maxEqualIdx(arr, k))
 
# This code is contributed by code_hunt
 
 

C#




// C# program for
// the above approach
using System;
class GFG{
 
// Function to find the maximum number of
// indices having equal elements after
// adding at most k numbers
public static int maxEqualIdx(int[] arr,
                              int k)
{
  // Sort the array in
  // ascending order
  Array.Sort(arr);
 
  // Make prefix sum array
  int[] prefixSum = new int[arr.Length + 1];
  prefixSum[1] = arr[0];
 
  for (int i = 1;
           i < prefixSum.Length - 1; ++i)
  {
    prefixSum[i + 1] = prefixSum[i] + arr[i];
  }
 
  // Initialize variables
  int max = arr.Length;
  int min = 1;
  int ans = 1;
 
  while (min <= max)
  {
    // Update mid
    int mid = (max + min) / 2;
 
    // Check if any subarray
    // can be obtained of length
    // mid having equal elements
    if (check(prefixSum, mid, k, arr))
    {
      ans = mid;
      min = mid + 1;
    }
    else
    {
      // Decrease max to mid
      max = mid - 1;
    }
  }
  return ans;
}
 
// Function to check if a subarray of
// length len consisting of equal elements
// can be obtained or not
public static bool check(int[] pSum,
                         int len, int k,
                         int[] a)
{
  // Sliding window
  int i = 0;
  int j = len;
  while (j <= a.Length)
  {
    // Last element of the sliding window
    // will be having the max size in the
    // current window
    int maxSize = a[j - 1];
 
    int totalNumbers = maxSize * len;
 
    // The current number of element in all
    // indices of the current sliding window
    int currNumbers = pSum[j] - pSum[i];
 
    // If the current number of the window,
    // added to k exceeds totalNumbers
    if (currNumbers + k >= totalNumbers)
    {
      return true;
    }
    else
    {
      i++;
      j++;
    }
  }
  return false;
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] arr = {1, 1, 1};
  int k = 7;
 
  // Function call
  Console.WriteLine(maxEqualIdx(arr, k));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
    // Function to find the maximum number of
    // indices having equal elements after
    // adding at most k numbers
    function maxEqualIdx(arr, k)
    {
        // Sort the array in
        // ascending order
        arr.sort();
 
        // Make prefix sum array
        let prefixSum
            = new Array(arr.length + 1).fill(0);
        prefixSum[1] = arr[0];
 
        for (let i = 1; i < prefixSum.length - 1;
             ++i) {
 
            prefixSum[i + 1]
                = prefixSum[i] + arr[i];
        }
 
        // Initialize variables
        let max = arr.length;
        let min = 1;
        let ans = 1;
 
        while (min <= max) {
 
            // Update mid
            let mid = Math.floor((max + min) / 2);
 
            // Check if any subarray
            // can be obtained of length
            // mid having equal elements
            if (check(prefixSum, mid, k, arr)) {
 
                ans = mid;
                min = mid + 1;
            }
            else {
 
                // Decrease max to mid
                max = mid - 1;
            }
        }
 
        return ans;
    }
 
    // Function to check if a subarray of
    // length len consisting of equal elements
    // can be obtained or not
    function check(pSum, len, k, a)
    {
 
        // Sliding window
        let i = 0;
        let j = len;
        while (j <= a.length) {
 
            // Last element of the sliding window
            // will be having the max size in the
            // current window
            let maxSize = a[j - 1];
 
            let totalNumbers = maxSize * len;
 
            // The current number of element in all
            // indices of the current sliding window
            let currNumbers = pSum[j] - pSum[i];
 
            // If the current number of the window,
            // added to k exceeds totalNumbers
            if (currNumbers + k >= totalNumbers) {
 
                return true;
            }
            else {
                i++;
                j++;
            }
        }
        return false;
    }
 
// Driver Code
 
        let arr = [ 1, 1, 1 ];
        let k = 7;
 
        // Function call
        document.write(maxEqualIdx(arr, k));
 
</script>
 
 
Output: 
3

 

Time Complexity: O(N * log N)
Auxiliary Space: O(N)



Next Article
Longest subarray not having more than K distinct elements
author
offbeat
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Searching
  • array-rearrange
  • Binary Search
  • sliding-window
  • subarray
Practice Tags :
  • Arrays
  • Binary Search
  • Mathematical
  • Searching
  • sliding-window

Similar Reads

  • Maximum sum of subarrays having distinct elements of length K
    Given an array, arr[] and a value k, represent the length of the subarray to be considered. Find the maximum sum that can be obtained from the subarray of length k such that each element of the subarray is unique. If there is no subarray that meets the required condition then return 0. Examples: Inp
    13 min read
  • Maximize length of subarray of equal elements by performing at most K increment operations
    Given an array A[] consisting of N integers and an integer K, the task is to maximize the length of the subarray having equal elements after performing at most K increments by 1 on array elements. Note: Same array element can be incremented more than once. Examples: Input: A[] = {2, 4, 8, 5, 9, 6},
    8 min read
  • Make sum of all subarrays of length K equal by only inserting elements
    Given an array arr[] of length N such that (1 <= arr[i] <= N), the task is to modify the array, by only inserting elements within the range [1, N], such that the sum of all subarrays of length K become equal. Print the modified array, if possible. Else print "Not possible".Examples: Input: arr
    7 min read
  • Longest subarray having sum of elements atmost K
    Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1}
    12 min read
  • Longest subarray not having more than K distinct elements
    Given N elements and a number K, find the longest subarray which has not more than K distinct elements.(It can have less than K). Examples: Input : arr[] = {1, 2, 3, 4, 5} k = 6 Output : 1 2 3 4 5 Explanation: The whole array has only 5 distinct elements which is less than k, so we print the array i
    8 min read
  • Maximize length of longest subarray consisting of same elements by at most K decrements
    Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray consisting of same elements that can be obtained by decrementing the array elements by 1 at most K times. Example: Input: arr[] = { 1, 2, 3 }, K = 1Output: 2Explanation:Decrementing arr[0] by 1 mo
    15+ min read
  • Length of Longest Subarray having at Most K Frequency
    Given an integer array arr[]and an integer K, the task is to find the length of the longest subarray such that the frequency of each element is less than or equal to K. Examples: Input: arr[] = {10, 20, 30, 10, 20, 30, 10, 20}, K = 2Output: 6Explanation: The longest possible subarray is {10, 20, 30,
    5 min read
  • Maximize MEX by adding or subtracting K from Array elements
    Given an arr[] of size N and an integer, K, the task is to find the maximum possible value of MEX by adding or subtracting K any number of times from the array elements. MEX is the minimum non-negative integer that is not present in the array Examples: Input: arr[]={1, 3, 4}, K = 2Output: 2Explanati
    7 min read
  • Maximum Subarray sum of A[] by adding any element of B[] at any end
    Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it: Choose either the leftmost or rightmost
    15 min read
  • Length of longest subarray having frequency of every element equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subarray such that each element occurs K times. Examples: Input: arr[] = {3, 5, 2, 2, 4, 6, 4, 6, 5}, K = 2Output: 8Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has freque
    9 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