Open In App

Maximize the smallest array element by incrementing all elements in a K-length subarray by 1 exactly M times

Last Updated : 13 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, and integers M and K, the task is to find the maximum possible value of the smallest array element by performing M operations. In each operation, increase the value of all elements in a contiguous subarray of length K by 1.

Examples:

Input: arr[ ] = {2, 2, 2, 2, 1, 1}, M = 1, K = 3
Output: 2
Explanation: Update the last 3 elements on the first move then updated array is [2, 2, 2, 3, 2, 2]. The smallest element has a value of 2.

Input: arr[ ] = {5, 8}, M = 5, K = 1
Output: 9

Approach: The problem can be solved by using Binary Search. Traverse the array arr[] and for every element arr[i], count the number of operations required. If the current element is required to be updated x times, then add x to the answer and update the consecutive segment of length K by x times.

Below is the implementation of the above approach:

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n, m, k, l, r, i;
 
// Function to check if the smallest
// value of v is achievable or not
ll check(ll v, vector<ll>& a)
{
    ll tec = 0, ans = 0;
 
    // Create array to
    // store previous moves
    vector<ll> b(n + k + 1);
 
    for (i = 0; i < n; i++) {
 
        // Remove previous moves
        tec -= b[i];
 
        if (a[i] + tec < v) {
 
            // Add balance to ans
            ll mov = v - a[i] - tec;
            ans = ans + mov;
 
            // Update contiguous
            // subarray of length k
            tec += mov;
            b[i + k] = mov;
        }
    }
 
    // Number of moves
    // should not exceed m
    return (ans <= m);
}
 
// Function to find the maximum
// value of the smallest array
// element that can be obtained
ll FindLargest(vector<ll> a)
{
    l = 1;
    r = pow(10, 10);
 
    // Perform Binary search
    while (r - l > 0) {
 
        ll tm = (l + r + 1) / 2;
 
        if (check(tm, a))
            l = tm;
        else
            r = tm - 1;
    }
    return l;
}
 
// Driver Code
int main()
{
    // Given Input
    vector<ll> a{ 2, 2, 2, 2, 1, 1 };
    m = 2;
    k = 3;
    n = a.size();
 
    // Function Call
    cout << FindLargest(a);
    return 0;
}


Java




// Java program for above approach
class GFG{
     
static long n, m, k, l, r, i;
 
// Function to check if the smallest
// value of v is achievable or not
static boolean check(long v, long[] a)
{
    long tec = 0, ans = 0;
     
    // Create array to
    // store previous moves
    long[] b = new long[(int)(n + k + 1)];
 
    for(int i = 0; i < n; i++)
    {
         
        // Remove previous moves
        tec -= b[i];
 
        if (a[i] + tec < v)
        {
             
            // Add balance to ans
            long mov = v - a[i] - tec;
            ans = ans + mov;
 
            // Update contiguous
            // subarray of length k
            tec += mov;
            b[i + (int)k] = mov;
        }
    }
 
    // Number of moves
    // should not exceed m
    return ans <= m;
}
 
// Function to find the maximum
// value of the smallest array
// element that can be obtained
static long FindLargest(long[] a)
{
    l = 1;
    r = (long)Math.pow(10, 10);
 
    // Perform Binary search
    while (r - l > 0)
    {
        long tm = (l + r + 1) / 2;
 
        if (check(tm, a))
            l = tm;
        else
            r = tm - 1;
    }
    return l;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Input
    long[] a = { 2, 2, 2, 2, 1, 1 };
    m = 2;
    k = 3;
    n = a.length;
 
    // Function Call
    System.out.println(FindLargest(a));
}
}
 
// This code is contributed by hritikrommie.


Python3




# Python 3 program for above approach
 
n = 0
m = 0
k = 0
l = 0
r = 0
i = 0
 
from math import pow
# Function to check if the smallest
# value of v is achievable or not
def check(v, a):
    tec = 0
    ans = 0
 
    # Create array to
    # store previous moves
    b = [0 for i in range(n + k + 1)]
 
    for i in range(n):
        # Remove previous moves
        tec -= b[i]
 
        if (a[i] + tec < v):
            # Add balance to ans
            mov = v - a[i] - tec
            ans = ans + mov
 
            # Update contiguous
            # subarray of length k
            tec += mov
            b[i + k] = mov
 
    # Number of moves
    # should not exceed m
    return (ans <= m)
 
# Function to find the maximum
# value of the smallest array
# element that can be obtained
def FindLargest(a):
    l = 1
    r = pow(10, 10)
 
    # Perform Binary search
    while (r - l > 0):
        tm = (l + r + 1) // 2
 
        if (check(tm, a)):
            l = tm
        else:
            r = tm - 1
    return l
 
# Driver Code
if __name__ == '__main__':
   
    # Given Input
    a = [2, 2, 2, 2, 1, 1]
    m = 2
    k = 3
    n = len(a)
 
    # Function Call
    print(int(FindLargest(a)))
     
    # This code is contributed by ipg2016107.


C#




// C# program for above approach
using System;
 
public class GFG
{
     
static long n, m, k, l, r, i;
 
// Function to check if the smallest
// value of v is achievable or not
static bool check(long v, long[] a)
{
    long tec = 0, ans = 0;
     
    // Create array to
    // store previous moves
    long[] b = new long[(int)(n + k + 1)];
 
    for(int i = 0; i < n; i++)
    {
         
        // Remove previous moves
        tec -= b[i];
 
        if (a[i] + tec < v)
        {
             
            // Add balance to ans
            long mov = v - a[i] - tec;
            ans = ans + mov;
 
            // Update contiguous
            // subarray of length k
            tec += mov;
            b[i + (int)k] = mov;
        }
    }
 
    // Number of moves
    // should not exceed m
    return ans <= m;
}
 
// Function to find the maximum
// value of the smallest array
// element that can be obtained
static long FindLargest(long[] a)
{
    l = 1;
    r = (long)Math.Pow(10, 10);
 
    // Perform Binary search
    while (r - l > 0)
    {
        long tm = (l + r + 1) / 2;
 
        if (check(tm, a))
            l = tm;
        else
            r = tm - 1;
    }
    return l;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Input
    long[] a = { 2, 2, 2, 2, 1, 1 };
    m = 2;
    k = 3;
    n = a.Length;
 
    // Function Call
    Console.WriteLine(FindLargest(a));
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
 
// Javascript program for above approach
let n = 0, m = 0, k = 0, l = 0, r = 0, i = 0;
 
// Function to check if the smallest
// value of v is achievable or not
function check(v, a)
{
    let tec = 0,
    ans = 0;
     
    // Create array to
    // store previous moves
    let b = new Array(n + k + 1).fill(0);
     
    for(i = 0; i < n; i++)
    {
         
        // Remove previous moves
        tec -= b[i];
         
        if (a[i] + tec < v)
        {
             
            // Add balance to ans
            let mov = v - a[i] - tec;
            ans = ans + mov;
             
            // Update contiguous
            // subarray of length k
            tec += mov;
            b[i + k] = mov;
        }
    }
     
    // Number of moves
    // should not exceed m
    return ans <= m;
}
 
// Function to find the maximum
// value of the smallest array
// element that can be obtained
function FindLargest(a)
{
    l = 1;
    r = Math.pow(10, 10);
     
    // Perform Binary search
    while (r - l > 0)
    {
        let tm = Math.floor((l + r + 1) / 2);
         
        if (check(tm, a)) l = tm;
        else r = tm - 1;
    }
    return l;
}
 
// Driver Code
 
// Given Input
let a = [ 2, 2, 2, 2, 1, 1 ];
m = 2;
k = 3;
n = a.length;
 
// Function Call
document.write(FindLargest(a));
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output: 

2

 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N + K)
 



Similar Reads

Maximize count of unique array elements by incrementing array elements by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of unique elements possible by increasing any array element by K only once. Examples: Input: arr[] = {0, 2, 4, 3, 4}, K = 1Output: 5Explanation:Increase arr[2] ( = 4) by K ( = 1). Therefore, new array is {0, 2, 4, 3, 5} which has 5 unique elements
8 min read
Find array sum after incrementing by K adjacent elements of every positive element M times
Given a circular array arr[] of N integers and two integer M and K, the task is to find the sum of array elements arr[] after performing M operations such that in each operation, increment the adjacent array elements of all the positive array element by K, i.e., if arr[i] &gt; 0, then increment the value of arr[i - 1] and arr[i + 1] by K. Examples:
14 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Maximize the product of digits by incrementing any digit X times
Given two integers N and X. Find the maximum product of digits of N, such that increment any digit by 1 at most X times ( chosen digit &lt; 9) Example: Input: N = 2, X = 2Output: 4Explanation: First Operation: Increment 2 to 3.Second Operation: Increment 3 to 4. Only a single digit is there. Therefore, the output is 4. Input: N = 2543, X = 4Output:
8 min read
Maximize sum of ratios of N given fractions by incrementing numerator and denominators K times by 1
Given a positive integer K and an array arr[] consisting of {numerator, denominator} of N fractions, the task is to find the sum of the ratio of the given fractions after incrementing numerators and denominators by 1, K number of times. Examples: Input: arr[][] = {{1, 2}, {3, 5}, {2, 2}}, K = 2Output: 0.78333Explanation:The most optimal choice is t
8 min read
Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K
Given an array arr[] of size N, the task is to find the smallest positive integer K such that incrementing or decrementing each array element by K at most once makes all elements equal. If it is not possible to make all array elements equal, then print -1. Examples : Input: arr[] = { 5, 7, 9 }Output: 2Explanation: Incrementing the value of arr[0] b
14 min read
Length of smallest Subarray with at least one element repeated K times
Given an array arr[] of length N and an integer K. The task is to find the minimum length of subarray such that at least one element of the subarray is repeated exactly K times in that subarray. If no such subarray exists, print -1. Examples: Input: arr[] = {1, 2, 1, 2, 1}, K = 2Output: 3Explanation: Subarray [1,2,1], have K = 2 occurrences of 1 In
9 min read
Maximize Array sum after incrementing at most K elements followed by dividing array by X
Given an array, arr[] and two integers, K and X, the task is to maximize the sum of the array elements after at most K increments of any elements, then dividing all of the elements by X Example: Input: arr = {16, 15, 17}, K = 8, X = 10Output: 5Explanation: At most 8 increments are allowed. So, increment element at index 0 by 4 and element at index
8 min read
Maximize distinct elements by incrementing/decrementing an element or keeping it same
Given an array arr[] of N elements, the task is to maximize the count of distinct elements in the array, by either of the given operation on each element of the array: either increasing the element by 1or decreasing the element by 1or keeping the element as it is. Note: No element can be less than or equal to 0. Examples: Input: arr = [4, 4, 5, 5,
6 min read
Kth smallest element in an array that contains A[i] exactly B[i] times
Given two arrays A[] and B[] consisting of N positive integers and an integer K, the task is to find the Kth smallest element in the array formed by taking the ith element from the array A[] exactly B[i] times. If there exists no such element, then print -1. Examples: Input: K = 4, A[] = {1, 2, 3}, B[] = {1, 2, 3} Output: 3Explanation:The array obt
7 min read