VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-the-maximum-value-in-array-by-incrementing-and-decrementing/

⇱ Minimize the maximum value in array by incrementing and decrementing. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the maximum value in array by incrementing and decrementing.

Last Updated : 23 Jul, 2025

Given array arr[] of size N, the task is to minimize the maximum value in given array by increasing arr[i] by 1 and decreasing arr[i + 1] by 1 any number of times.

Examples:

Input: arr[] = {3, 7, 1, 6}
Output: 5
Explanation: Initially we have arr[] = {3, 7, 1, 6}

  • Choose i = 1 (considering 1 index), arr[] becomes {4, 6, 1, 6}
  • Choose i = 1, arr[] becomes {5, 5, 1, 6}
  • Choose i = 3, arr[] becomes {5, 5, 2, 5}
    5 is the minimum number we can get by performing above operations any number of times

Input: arr[] = {10, 1}
Output: 10
Explanation: 10 is the minimum number we can get by performing above operations any number of times.

Approach: Implement the idea below to solve the problem

Binary Search can be used to solve this problem. Idea is for every number we can check whether it is possible to make it as maximum element of array or not by performing given operations. We will binary search on this monotonic function it will be of type FFFFFTTTTT initially function will be false for smaller values and as the values increase it will keep returning true. We have to find first time when function becomes true.

Step-by-step approach:

  • Declare function test() to check if it is possible to make maximum value of array at most mid
    • Declare variable prev which is initially set to zero (which is extra number that we need to carry backwards so to make i'th element at most mid)
    • Iterate i from N - 1 to 1 and follow given steps for each i:
      • if sum of A[i] and prev is greater than mid update prev as A[i] + prev - mid
      • else make prev as 0
    • finally return whether sum of first element and prev is less than equal to mid or not
  • Declare low = 0 and high as sum of array A[]
  • Run while loop till high and low are not adjacent
    • Declare variable mid set as (low + high) / 2
    • if test function is true for mid update high as mid otherwise low as mid + 1
  • if test() function is true for low return low otherwise return high

Below is the implementation of the above approach:


Output
5

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

Comment