![]() |
VOOZH | about |
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 timesInput: 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:
Below is the implementation of the above approach:
5
Time Complexity: O(N log (N))
Auxiliary Space: O(N)