Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Minimize The Difference
EASY
20 mins
60 upvotes
Greedy
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Greedy
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Minimize The Difference

Contributed by
Nihal Srivastava
Easy
yellow-spark
0/40
Avg time to solve 20 mins
Success Rate 70 %
Share
60 upvotes

Problem Statement

You are given an array ‘A’ of length ‘N’ consisting only of positive integers and an integer ‘K’. You have to update every element of the array by increasing or decreasing its value by ‘K’ only once. Your task is to minimize the difference between maximum and minimum elements of the array after performing the increment or decrement on every element of the array.

Note: After the operation, every value of the array should remain non-negative.

For example:

Let’s say the array ‘A’ = [1, 2, 3, 4, 5] and ‘K’ = 2, then after increasing each element by ‘K’. The array ‘A’ will become [3, 4, 5, 6, 7]. So the maximum - minimum will be 7 - 3 = 4. 
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input-1
2
4 2
1 5 8 10
5 2
1 2 3 4 5
Sample Output-1
5
3
Explanation for Sample Input 1:
For test case 1:
    The final array will look like [3, 3, 6, 8]. So the difference between maximum and minimum is 8 - 3 = 5.
For test case 2:
    The final array will look like [3, 4, 1, 2, 3]. So the difference between maximum and minimum is 4 - 1 = 3.
Sample Input -2
2
1 2
8
3 2
1 3 3
Sample Output -2
0
2
Reset Code
Full screen
Auto
copy-code
Console