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 first array element by performing given operations at most K times
Next article icon

Maximize length of subarray of equal elements by performing at most K increment operations

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

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}, K = 6
Output: 3
Explanation:
Subarray [8, 5, 9] can be modified to [9, 9, 9].
Total number of increments required is 5 which is less than K(= 6).

Input: A[] = {2, 2, 4}, K = 10
Output: 3

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if all its elements can be made equal in at most K increments. Print the maximum length of such subarrays obtained. 

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

Approach: The above approach can be optimized using the Sliding Window technique. Follow the steps below to solve the problem:

  • Keep a track of the maximum element of the window.
  • The total operations required for a particular window is obtained by the following equation:

Count of operations = (Length of the window calculated so far + 1) * (Maximum element from the window) – Sum of the window

  • Now, check if the above-calculated value exceeds K or not. If so, then slide the starting pointer of the window towards the right, otherwise increment the length of the window calculated so far.
  • Repeat the above steps to obtain the longest window satisfying the required condition.

Below is the implementation of the above approach:

C++14




// C++14 program for above approach
#include <bits/stdc++.h>
using namespace std;
#define newl "\n"
 
// Function to find the maximum length
// of subarray of equal elements after
// performing at most K increments
int maxSubarray(int a[], int k, int n)
{
 
    // Stores the size
    // of required subarray
    int answer = 0;
 
    // Starting point of a window
    int start = 0;
 
    // Stores the sum of window
    long int s = 0;
 
    deque<int> dq;
 
    // Iterate over array
    for(int i = 0; i < n; i++)
    {
         
        // Current element
        int x = a[i];
 
        // Remove index of minimum elements
        // from deque which are less than
        // the current element
        while (!dq.empty() &&
               a[dq.front()] <= x)
            dq.pop_front();
 
        // Insert current index in deque
        dq.push_back(i);
 
        // Update current window sum
        s += x;
 
        // Calculate required operation to
        // make current window elements equal
        long int cost = (long int)a[dq.front()] *
                        (answer + 1) - s;
 
        // If cost is less than k
        if (cost <= (long int)k)
            answer++;
 
        // Shift window start pointer towards
        // right and update current window sum
        else
        {
            if (dq.front() == start)
                dq.pop_front();
                 
            s -= a[start++];
        }
    }
     
    // Return answer
    return answer;
}
 
// Driver Code
int main()
{
    int a[] = { 2, 2, 4 };
    int k = 10;
     
    // Length of array
    int n = sizeof(a) / sizeof(a[0]);
     
    cout << (maxSubarray(a, k, n));
     
    return 0;
}
 
// This code is contributed by jojo9911
 
 

Java




// Java Program for above approach
import java.util.*;
 
class GFG {
 
    // Function to find the maximum length
    // of subarray of equal elements after
    // performing at most K increments
    static int maxSubarray(int[] a, int k)
    {
        // Length of array
        int n = a.length;
 
        // Stores the size
        // of required subarray
        int answer = 0;
 
        // Starting point of a window
        int start = 0;
 
        // Stores the sum of window
        long s = 0;
 
        Deque<Integer> dq = new LinkedList<>();
 
        // Iterate over array
        for (int i = 0; i < n; i++) {
 
            // Current element
            int x = a[i];
 
            // Remove index of minimum elements
            // from deque which are less than
            // the current element
            while (!dq.isEmpty() && a[dq.peek()] <= x)
                dq.poll();
 
            // Insert current index in deque
            dq.add(i);
 
            // Update current window sum
            s += x;
 
            // Calculate required operation to
            // make current window elements equal
            long cost
                = (long)a[dq.peekFirst()] * (answer + 1)
                  - s;
 
            // If cost is less than k
            if (cost <= (long)k)
                answer++;
 
            // Shift window start pointer towards
            // right and update current window sum
            else {
                if (dq.peekFirst() == start)
                    dq.pollFirst();
                s -= a[start++];
            }
        }
 
        // Return answer
        return answer;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int[] a = { 2, 2, 4 };
        int k = 10;
 
        // Function call
        System.out.println(maxSubarray(a, k));
    }
}
 
 

Python3




# Python3 program for above approach
from collections import deque
 
# Function to find the maximum length
# of subarray of equal elements after
# performing at most K increments
def maxSubarray(a, k):
     
    # Length of array
    n = len(a)
 
    # Stores the size
    # of required subarray
    answer = 0
 
    # Starting po of a window
    start = 0
 
    # Stores the sum of window
    s = 0
 
    dq = deque()
 
    # Iterate over array
    for i in range(n):
 
        # Current element
        x = a[i]
 
        # Remove index of minimum elements
        # from deque which are less than
        # the current element
        while (len(dq) > 0 and a[dq[-1]] <= x):
            dq.popleft()
 
        # Insert current index in deque
        dq.append(i)
 
        # Update current window sum
        s += x
 
        # Calculate required operation to
        # make current window elements equal
        cost = a[dq[0]] * (answer + 1) - s
 
        # If cost is less than k
        if (cost <= k):
            answer += 1
 
        # Shift window start pointer towards
        # right and update current window sum
        else:
            if (dq[0] == start):
                dq.popleft()
                 
            s -= a[start]
            start += 1
 
    # Return answer
    return answer
 
# Driver Code
if __name__ == '__main__':
     
    a = [ 2, 2, 4 ]
    k = 10
 
    # Function call
    print(maxSubarray(a, k))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# Program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the maximum length
// of subarray of equal elements after
// performing at most K increments
static int maxSubarray(int[] a, int k)
{
  // Length of array
  int n = a.Length;
 
  // Stores the size
  // of required subarray
  int answer = 0;
 
  // Starting point of a window
  int start = 0;
 
  // Stores the sum of window
  long s = 0;
 
  Queue<int> dq = new Queue<int>();
 
  // Iterate over array
  for (int i = 0; i < n; i++)
  {
    // Current element
    int x = a[i];
 
    // Remove index of minimum
    // elements from deque
    // which are less than
    // the current element
    while (dq.Count!=0 &&
           a[dq.Peek()] <= x)
      dq.Dequeue();
 
    // Insert current
    // index in deque
    dq.Enqueue(i);
 
    // Update current window sum
    s += x;
 
    // Calculate required operation to
    // make current window elements equal
    long cost = (long)a[dq.Peek()] *
                (answer + 1) - s;
 
    // If cost is less than k
    if (cost <= (long)k)
      answer++;
 
    // Shift window start pointer towards
    // right and update current window sum
    else
    {
      if (dq.Peek() == start)
        dq.Dequeue();
      s -= a[start++];
    }
  }
 
  // Return answer
  return answer;
}
 
// Driver Code
public static void Main(String[] args)
{
  int[] a = {2, 2, 4};
  int k = 10;
 
  // Function call
  Console.WriteLine(maxSubarray(a, k));
}
}
 
// This code is contributed by gauravrajput1
 
 

Javascript




<script>
 
// Javascript program for above approach
 
// Function to find the maximum length
// of subarray of equal elements after
// performing at most K increments
function maxSubarray(a, k, n)
{
 
    // Stores the size
    // of required subarray
    var answer = 0;
 
    // Starting point of a window
    var start = 0;
 
    // Stores the sum of window
    var s = 0;
 
    var dq = [];
 
    // Iterate over array
    for(var i = 0; i < n; i++)
    {
         
        // Current element
        var x = a[i];
 
        // Remove index of minimum elements
        // from deque which are less than
        // the current element
        while (dq.length!=0 &&
               a[dq[0]] <= x)
            dq.shift();
 
        // Insert current index in deque
        dq.push(i);
 
        // Update current window sum
        s += x;
 
        // Calculate required operation to
        // make current window elements equal
        var cost = a[dq[0]] *
                        (answer + 1) - s;
 
        // If cost is less than k
        if (cost <= k)
            answer++;
 
        // Shift window start pointer towards
        // right and update current window sum
        else
        {
            if (dq[0] == start)
                dq.shift();
                 
            s -= a[start++];
        }
    }
     
    // Return answer
    return answer;
}
 
// Driver Code
var a = [2, 2, 4];
var k = 10;
 
// Length of array
var n = a.length;
 
document.write(maxSubarray(a, k, n));
 
 
</script>
 
 
Output: 
3

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



Next Article
Maximize first array element by performing given operations at most K times
author
offbeat
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Queue
  • Searching
  • deque
  • Google
  • sliding-window
  • subarray
Practice Tags :
  • Google
  • Arrays
  • Deque
  • Mathematical
  • Queue
  • Searching
  • sliding-window

Similar Reads

  • Maximize length of subarray having equal elements by adding at most K
    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
    9 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
  • Maximize first array element by performing given operations at most K times
    Given an array arr[] of size N an integer K, the task is to find the maximize the first element of the array by performing the following operations at most K times: Choose a pair of indices i and j (0 ? i, j ? N-1) such that |i ? j| = 1 and arri > 0.Set arri = arri ? 1 and arrj = arrj + 1 on thos
    7 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
  • Make the array elements equal by performing given operations minimum number of times
    Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
    7 min read
  • Maximize sum of array elements removed by performing the given operations
    Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations: Choose an index i an
    8 min read
  • Minimum number of increment-other operations to make all array elements equal.
    We are given an array consisting of n elements. At each operation we can select any one element and increase rest of n-1 elements by 1. We have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this. Examples: Input: arr[] =
    5 min read
  • Longest subarray whose elements can be made equal by maximum K increments
    Given an array arr[] of positive integers of size N and a positive integer K, the task is to find the maximum possible length of a subarray which can be made equal by adding some integer value to each element of the sub-array such that the sum of the added elements does not exceed K. Examples: Input
    12 min read
  • Minimum increment operations to make K elements equal
    Given an array arr[] of N elements and an integer K, the task is to make any K elements of the array equal by performing only increment operations i.e. in one operation, any element can be incremented by 1. Find the minimum number of operations required to make any K elements equal.Examples: Input:
    11 min read
  • Minimum number of operations to make maximum element of every subarray of size K at least X
    Given an array A[] of size N and an integer K, find minimum number of operations to make maximum element of every subarray of size K at least X. In one operation, we can increment any element of the array by 1. Examples: Input: A[] = {2, 3, 0, 0, 2}, K = 3, X =4Output: 3Explanation: Perform followin
    7 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