Minimize The Maximum
You are given an array of N integers and an integer K. For each array element, you are allowed to increase or decrease it by a value k. The task is to minimize the difference between the maximum element and the minimum element after modifications.
Input Format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the test cases follow.
The first line of each test case contains a positive integer N which represents the number of elements of an array.
The Second line of each test case contains N integers denoting the elements of the array.
The third line of each test case contains a positive integer K.
Output Format :
For each test case, return the minimum difference between the maximum element and minimum element of the array by either increasing or decreasing elements of the array by K.
Note:
You do not need to print anything. It has already been taken care of.
Constraints :
1 <= T <= 5
1 <= N <= 10^5
0 <= arr[i] <= 10^5
0 <= K <= 10^5
Time limit = 1 sec
CodingNinjas
author
2y
Brute Force
For every element, we have two choices either increase it by k or decrease it by k.
- Initialize a global variable ans to the maximum value.
- Call a helper function that takes an array, k, in...read more
CodingNinjas
author
2y
Optimal Approach
The big thing to observe is that for any given element, if you choose to increase its height from hi to hi + k, then you might as well increase all shorter elements: that won't affect ...read more
Help your peers!
Add answer anonymously...
Top TCS System Engineer interview questions & answers
Popular interview questions of System Engineer
Top HR questions asked in TCS System Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app