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:
Number of subarrays with at-least K size and elements not greater than M
Next article icon

Minimum number of operations to make maximum element of every subarray of size K at least X

Last Updated : 29 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 =4
Output: 3
Explanation: Perform following operation to make every subarray of size 3 at least X = 4

  • Choose index i = 1 (A[1] = 3) and increment by 1, A[1] becomes 4.
  • Choose index i = 4 (A[4] = 2) and increment by 1, A[4] becomes 3.
  • Choose index i = 4 (A[4] = 3) and increment by 1, A[4] becomes 4.

After 3 operations array A[] becomes {2, 4, 0, 0, 4} whose every subarray of size 3 is at least X = 4

Input: A[] = {0, 1, 3, 3}, K = 3, X = 5
Output: 2
Explanation: Perform following operation to make every subarray of size 3 at least X = 5

  • Choose index i = 2 (A[2] = 3) and increment by 1, A[2] becomes 4.
  • Choose index i = 2 (A[2] = 3) and increment by 1, A[2] becomes 5.

After 2 operations A[] becomes {0, 1, 5, 3} whose every subarray of size 3 is at least X = 5.

Approach: Implement the idea below to solve the problem

The problem can be solved using Dynamic Programming. Since any element can belong to at most 3 subarrays, we have K cases for any index i:

  • Case 1: Increment ith index and move to index (i+1)
  • Case 2: Increment (i + 1)th index and move to index (i + 2)
  • Case 3: Increment (i + 2)th index and move to index (i + 3)
  • ....
  • Case K: Increment (i + K - 1)th index and move to index (i + K)

Now, we can explore all the cases to get the answer.

Steps to solve the problem:

  • Maintain a recursive function minOperations(idx, X, N, K) to return the answer from index idx to index N-1.
  • Iterate from i = 0 to i = K-1,
    • Explore the case where we increment A[idx + i] and call minOperations(idx + i + 1, X, N, K).
    • Minimize the answer over all choices.
  • Return the minimum operations required.

Code to implement the approach:

C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;  // Function to return minimum number of operations to // make maximum element of every subarray of size K // at least X in from index = idx to N-1 int minOperations(int A[], int idx, int X, int N, int K,                   vector<long long>& dp) {     // if a subarray of size K cannot be formed at index idx     if (idx > N - K)         return 0;     // If the answer is already calculated, return it     if (dp[idx] != -1)         return dp[idx];     long long ans = 1e18;     // Explore all the choices     for (int i = 0; i < K; i++) {         long long choose             = max(0, X - A[idx + i])               + minOperations(A, idx + i + 1, X, N, K, dp);         ans = min(ans, choose);     }      return dp[idx] = ans; }  // Driver Code int main() {      // Input     int N = 5, X = 4, K = 3;     int A[] = { 2, 3, 0, 0, 2 };     vector<long long> dp(N, -1);      // Function Call     cout << minOperations(A, 0, X, N, K, dp) << endl;      return 0; } 
Java
import java.util.Arrays;  public class MinimumOperations {      // Function to return minimum number of operations to     // make the maximum element of every subarray of size K     // at least X from index idx to N-1     static int minOperations(int[] A, int idx, int X, int N, int K, int[] dp) {         // If a subarray of size K cannot be formed at index idx         if (idx > N - K) {             return 0;         }         // If the answer is already calculated, return it         if (dp[idx] != -1) {             return dp[idx];         }         int ans = Integer.MAX_VALUE;         // Explore all the choices         for (int i = 0; i < K; i++) {             int choose = Math.max(0, X - A[idx + i]) +                     minOperations(A, idx + i + 1, X, N, K, dp);             ans = Math.min(ans, choose);         }          dp[idx] = ans;         return ans;     }      // Driver Code     public static void main(String[] args) {         // Input         int N = 5, X = 4, K = 3;         int[] A = {2, 3, 0, 0, 2};         int[] dp = new int[N];         Arrays.fill(dp, -1);          // Function Call         System.out.println(minOperations(A, 0, X, N, K, dp));     } } 
Python3
# Function to return minimum number of operations to # make the maximum element of every subarray of size K # at least X from index idx to N-1   def min_operations(A, idx, X, N, K, dp):     # if a subarray of size K cannot be formed at index idx     if idx > N - K:         return 0     # If the answer is already calculated, return it     if dp[idx] != -1:         return dp[idx]     ans = float('inf')     # Explore all the choices     for i in range(K):         choose = max(0, X - A[idx + i]) + \             min_operations(A, idx + i + 1, X, N, K, dp)         ans = min(ans, choose)      dp[idx] = ans     return ans   # Driver Code if __name__ == "__main__":     # Input     N, X, K = 5, 4, 3     A = [2, 3, 0, 0, 2]     dp = [-1] * N      # Function Call     print(min_operations(A, 0, X, N, K, dp)) 
C#
// C# program for the above approach using System;  public class GFG {     // Function to return minimum number of operations to     // make the maximum element of every subarray of size K     // at least X from index idx to N-1     static int MinOperations(int[] A, int idx, int X, int N,                              int K, int[] dp)     {         // If a subarray of size K cannot be formed at index         // idx         if (idx > N - K) {             return 0;         }          // If the answer is already calculated, return it         if (dp[idx] != -1) {             return dp[idx];         }          int ans = int.MaxValue;          // Explore all the choices         for (int i = 0; i < K; i++) {             int choose = Math.Max(0, X - A[idx + i])                          + MinOperations(A, idx + i + 1, X,                                          N, K, dp);             ans = Math.Min(ans, choose);         }          dp[idx] = ans;         return ans;     }      // Driver Code     static void Main()     {         // Input         int N = 5, X = 4, K = 3;         int[] A = { 2, 3, 0, 0, 2 };         int[] dp = new int[N];         for (int i = 0; i < N; i++) {             dp[i] = -1;         }          // Function Call         Console.WriteLine(MinOperations(A, 0, X, N, K, dp));     } }  // This code is contributed by Susobhan Akhuli 
JavaScript
// Function to return minimum number of operations to // make the maximum element of every subarray of size K // at least X from index idx to N-1 function minOperations(A, idx, X, N, K, dp) {     // if a subarray of size K cannot be formed at index idx     if (idx > N - K) {         return 0;     }     // If the answer is already calculated, return it     if (dp[idx] !== -1) {         return dp[idx];     }     let ans = Infinity;     // Explore all the choices     for (let i = 0; i < K; i++) {         const choose = Math.max(0, X - A[idx + i]) +             minOperations(A, idx + i + 1, X, N, K, dp);         ans = Math.min(ans, choose);     }      dp[idx] = ans;     return ans; }  // Driver Code // Input const N = 5, X = 4, K = 3; const A = [2, 3, 0, 0, 2]; const dp = Array(N).fill(-1);  // Function Call console.log(minOperations(A, 0, X, N, K, dp)); 

Output
3

Time Complexity: O(N), where N is the size of the input array A[].
Auxiliary Space: O(N)


Next Article
Number of subarrays with at-least K size and elements not greater than M
author
iamkiran2233
Improve
Article Tags :
  • Competitive Programming
  • Geeks Premier League
  • DSA
  • Arrays
  • Algorithms-Dynamic Programming
  • Geeks Premier League 2023
Practice Tags :
  • Arrays

Similar Reads

  • Minimize operations to make all array elements -1 by changing maximums of K-size subarray to -1
    Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum of operations required to make all the array elements -1 such that in each operation, choose a subarray of size K and change all the maximum element in the subarray to -1. Examples: Input: arr[] = {18, 11
    8 min read
  • Sum of minimum and maximum elements of all subarrays of size k.
    Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k. Examples: Input : arr[] = {2, 5, -1, 7, -3, -1, -2} K = 4Output : 18Explanation : Subarrays of size 4 are : {2, 5, -1, 7}, min + max = -1 + 7 = 6 {5, -1, 7, -
    15+ min read
  • Maximize the sum of maximum elements of at least K-sized subarrays
    Given an integer array arr[] of length N and an integer K, partition the array in some non-overlapping subarrays such that each subarray has size at least K and each element of the array should be part of a subarray. The task is to maximize the sum of maximum elements across all the subarrays. Examp
    7 min read
  • Maximize sum of each element raised to power of its frequency in K sized subarray
    Given an array arr[] of N elements and an integer K. The task is to find the maximum sum of elements in a subarray of size K, with each element raised to the power of its frequency in the subarray. Examples: Input: arr[] = { 2, 1, 2, 3, 3 }, N = 5, K = 3Output: 11Explanation: Required subarray of si
    15 min read
  • Number of subarrays with at-least K size and elements not greater than M
    Given an array of N elements, K is the minimum size of the sub-array, and M is the limit of every element in the sub-array, the task is to count the number of sub-arrays with a minimum size of K and all the elements are lesser than or equal to M. Examples: Input: arr[] = {-5, 0, -10}, K = 1, M = 15O
    7 min read
  • Maximum number of Armstrong Numbers present in a subarray of size K
    Given an array arr[] consisting of N integers and a positive integer K, the task is to find the maximum count of Armstrong Numbers present in any subarray of size K. Examples: Input: arr[] = {28, 2, 3, 6, 153, 99, 828, 24}, K = 6Output: 4Explanation: The subarray {2, 3, 6, 153} contains only of Arms
    12 min read
  • Maximum sum of lengths of non-overlapping subarrays with k as the max element.
    Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element. Examples: Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4} k = 4 Output : 5 {2, 1, 4} => Length = 3 {3, 4} => Length = 2 So, 3 + 2 = 5 is the answer Input : arr[] = {1, 2, 3, 2, 3, 4, 1
    15+ min read
  • Maximum number of Perfect Numbers present in a subarray of size K
    Given an array arr[ ] consisting of N integers, the task is to determine the maximum number of perfect Numbers in any subarray of size K. Examples: Input: arr[ ] = {28, 2, 3, 6, 496, 99, 8128, 24}, K = 4Output: 3Explanation: The sub-array {6, 496, 99, 8128} has 3 perfect numbers which is maximum. In
    10 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
  • Find maximum (or minimum) sum of a subarray of size k
    Given an array of integers and a number k, find the maximum sum of a subarray of size k. Examples: Input : arr[] = {100, 200, 300, 400}, k = 2Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39Explanation: We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. Inp
    14 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